<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Traits\ApiResponseTrait;
use App\Models\StatutoryMaster;
use App\Models\UserDeleteLog;
use Illuminate\Support\Str;
use App\Models\StatutorySections;


class StatutoryController extends Controller
{
    use ApiResponseTrait;

    /**
     * CREATE STATUTORY
     */
    public function createStatutory(Request $request)
    {
        $data = $request->validate([
            'state_id'          => 'required|exists:state_master,id',
            'act_name'          => 'required|string',
            'submission_authority_id' => 'required|integer',
            'form_no'           => 'required|string',
            'description'       => 'required|string',
            'classifications'   => 'required|string',
            'periodicity'       => 'required|string',
            'jurisdiction_type'    => 'required|string',
            'remarks'           => 'nullable|string',
        ]);

        $statutoryCode = $this->generateStatutoryCode();

        $statutory = StatutoryMaster::create(array_merge($data, [
            'statutory_code' => $statutoryCode,
            'is_active'  => 1,
            'is_deleted' => 0,
        ]));

        return $this->successResponse(
            'Statutory record created successfully',
            $statutory
        );
    }

    /**
     * UPDATE STATUTORY
     */
    public function updateStatutory(Request $request, $id)
    {
        $statutory = StatutoryMaster::where('id', $id)
            ->where('is_deleted', 0)
            ->first();

        if (!$statutory) {
            return $this->errorResponse('Statutory record not found', null, 404);
        }

        $data = $request->validate([
            'state_id'          => 'required|exists:state_master,id',
            'act_name'          => 'required|string',
            'submission_authority_id' => 'required|integer',
            'form_no'           => 'required|string',
            'description'       => 'required|string',
            'classifications'   => 'required|string',
            'periodicity'       => 'required|string',
            'jurisdiction_type'    => 'required|string',
            'remarks'           => 'nullable|string',
            'is_active'                    => 'required|integer',

        ]);

        $statutory->update($data);

        return $this->successResponse(
            'Statutory record updated successfully'
        );
    }

    /**
     * GET SINGLE STATUTORY
     */
    public function getStatutory($id)
    {
        $statutory = StatutoryMaster::where('id', $id)
            ->where('is_deleted', 0)
            ->with('state_master')
            ->with('submission_authority_master')
            ->with('statutory_sections')
            ->first();

        if (!$statutory) {
            return $this->errorResponse('Statutory record not found', null, 404);
        }

        return $this->successResponse(
            'Statutory record fetched successfully',
            $statutory
        );
    }

    /**
     * LIST STATUTORY
     */
    public function listStatutory(Request $request)
    {
        $query = StatutoryMaster::where('is_deleted', 0)
            ->with('state_master')
            ->with('statutory_sections')
            ->with('submission_authority_master');

        if ($request->filled('state_id')) {
            $query->where('state_id', $request->state_id);
        }

        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        $statutory = $query
            ->orderBy('act_name')
            ->get();

        return $this->successResponse(
            'Statutory list fetched successfully',
            $statutory
        );
    }

    /**
     * DELETE STATUTORY (SOFT DELETE)
     */
    public function deleteStatutory(Request $request, $id)
    {
        $statutory = StatutoryMaster::where('id', $id)
            ->where('is_deleted', 0)
            ->first();

        if (!$statutory) {
            return $this->errorResponse('Statutory record not found', null, 404);
        }

        UserDeleteLog::create([
            'table_id' => $id,
            'table_name'  => 'statutory_master',
            'reason' => $request['reason'],
        ]);

        $statutory->update([
            'is_deleted' => 1
        ]);

        return $this->successResponse('Statutory record deleted successfully');
    }

    private function generateStatutoryCode()
    {
        do {
            // Generate 5-character alphanumeric code
            $code = strtoupper(Str::random(5));

            // Check if already exists
            $exists = StatutoryMaster::where('statutory_code', $code)->exists();
        } while ($exists); // If exists → repeat

        return $code;
    }

    public function createStatutorySection(Request $request)
    {
        $data = $request->validate([
            'statutory_id'        => 'required|exists:statutory_master,id',
            'section'             => 'required|string',
            'form'                => 'required|string',
            'nature_of_compliance' => 'required|string',
            'remarks'             => 'nullable|string',
        ]);

        $section = StatutorySections::create([
            ...$data,
            'is_active'  => 1,
            'is_deleted' => 0,
        ]);

        return $this->successResponse(
            'Statutory section created successfully',
            $section
        );
    }

    public function listStatutorySections(Request $request)
    {
        $query = StatutorySections::where('is_deleted', 0);

        if ($request->filled('statutory_id')) {
            $query->where('statutory_id', $request->statutory_id);
        }

        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active);
        }

        $sections = $query
            ->orderBy('section')
            ->get();

        return $this->successResponse(
            'Statutory sections fetched successfully',
            $sections
        );
    }


    public function getStatutorySection($id)
    {
        $section = StatutorySections::where('id', $id)
            ->where('is_deleted', 0)
            ->first();

        if (!$section) {
            return $this->errorResponse('Statutory section not found', null, 404);
        }

        return $this->successResponse(
            'Statutory section fetched successfully',
            $section
        );
    }

    public function updateStatutorySection(Request $request, $id)
    {
        $section = StatutorySections::where('id', $id)
            ->where('is_deleted', 0)
            ->first();

        if (!$section) {
            return $this->errorResponse('Statutory section not found', null, 404);
        }

        $data = $request->validate([
            'section'              => 'required|string',
            'form'                 => 'required|string',
            'nature_of_compliance' => 'required|string',
            'remarks'              => 'nullable|string',
            'is_active'            => 'required|integer',

        ]);

        $section->update($data);

        return $this->successResponse(
            'Statutory section updated successfully'
        );
    }

    public function updateStatutorySectionStatus(Request $request, $id)
    {
        $section = StatutorySections::where('id', $id)
            ->where('is_deleted', 0)
            ->first();

        if (!$section) {
            return $this->errorResponse('Statutory section not found', null, 404);
        }

        $data = $request->validate([
            'is_active' => 'required|integer|in:0,1',
        ]);

        $section->update($data);

        return $this->successResponse(
            'Statutory section status updated successfully'
        );
    }

   public function deleteStatutorySection(Request $request, $id)
{
    $section = StatutorySections::where('id', $id)->first();

    if (!$section) {
        return $this->errorResponse('Statutory section not found', null, 404);
    }

    // Optional: log delete reason
    // UserDeleteLog::create([
    //     'table_id'   => $id,
    //     'table_name' => 'statutory_sections',
    //     'reason'     => $request->reason,
    // ]);

    // PERMANENT DELETE
    $section->delete();

    return $this->successResponse(
        'Statutory section deleted successfully'
    );
}

}
