<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\ClearanceTemplate;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class ClearanceTemplateController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        //
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $data = ClearanceTemplate::with('job_classification')->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('name', 'like', '%' . $keyword . '%');
        });

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);

        // Fix: Use through() method to transform paginated items
        $data->through(function ($item) {
            $item->encrypted_id = Crypt::encrypt($item->id);
            return $item;
        });

        return response()->json($data);
    }

    public function show(string $id)
    {
        $data = ClearanceTemplate::where('employee_id', '=',$id)->get();
        
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'min:2',
            ]
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {

            $data = ClearanceTemplate::create($request->all());

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully added!',
                'status' => 'success',
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function update(Request $request, int $id)
    {
        $data = ClearanceTemplate::where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                'name' => [
                    'required',
                    'min:2',
                ]
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {

            $data->fill($request->all());
            $data->save();

            $data->touch();

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function updateSignatory(Request $request, string $id)
    {
        try {
            $decrypted_id = Crypt::decrypt($id);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 400,
                'message' => 'Invalid template ID',
                'error' => 'Failed to decrypt ID'
            ], 400);
        }

        // Validate the request
        $validated = $request->validate([
            'sections' => 'required|array',
            'sections.*.name' => 'required|string',
            'sections.*.areas' => 'required|array',
            'sections.*.areas.*.name' => 'required|string',
            'sections.*.areas.*.items' => 'required|array',
            'sections.*.areas.*.items.*.code' => 'required|string',
            'sections.*.areas.*.items.*.name' => 'required|string',
            'sections.*.areas.*.items.*.sla_primary' => 'required|integer|min:0',
            'sections.*.areas.*.items.*.sla_secondary' => 'required|integer|min:0',
            'sections.*.areas.*.items.*.primary_officer' => 'nullable|string',
            'sections.*.areas.*.items.*.secondary_officer' => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            // Find the template - use findOrFail to throw exception if not found
            $template = ClearanceTemplate::where("id", $decrypted_id)->first();

            // If the above doesn't work, the template doesn't exist
            if (!$template) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Clearance template not found',
                    'template_id' => $decrypted_id
                ], 404);
            }

            // Prepare signatory data for counting
            $signatoryData = [];
            
            foreach ($validated['sections'] as $section) {
                foreach ($section['areas'] as $area) {
                    foreach ($area['items'] as $item) {
                        $signatoryData[] = [
                            'section_name' => $section['name'],
                            'area_name' => $area['name'],
                            'item_code' => $item['code'],
                            'item_name' => $item['name'],
                            'sla_primary' => $item['sla_primary'],
                            'sla_secondary' => $item['sla_secondary'],
                            'primary_officer_id' => $item['primary_officer'] ?: null,
                            'secondary_officer_id' => $item['secondary_officer'] ?: null,
                        ];
                    }
                }
            }
            
            // Store as JSON in clearance_templates table
            $template->signatories = json_encode($validated['sections']);
            $template->updated_at = now();
            $template->save();
            
            DB::commit();

            return response()->json([
                'status' => 200,
                'message' => 'Signatories updated successfully',
                'data' => [
                    'id' => $decrypted_id,
                    'total_items' => count($signatoryData),
                    'template_name' => $template->name ?? 'N/A'
                ]
            ], 200);

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            DB::rollBack();
            
            return response()->json([
                'status' => 404,
                'message' => 'Clearance template not found',
                'template_id' => $decrypted_id
            ], 404);
            
        } catch (\Exception $e) {
            DB::rollBack();
            
            return response()->json([
                'status' => 500,
                'message' => 'Failed to update signatories',
                'error' => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ], 500);
        }
    }

    public function getSignatories(string $id)
    {
        $id = Crypt::decrypt($id);

        $data = ClearanceTemplate::where('id', $id)->first();
        
        return response()->json($data);
    }

    public function destroy(int $id)
    {
        $data = ClearanceTemplate::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }
}