<?php

namespace App\Http\Controllers;

use App\Models\WhsqReport;
use App\Models\WhsqSignature;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Exception;
use App\Models\EmpCompanyDetails;
use App\Models\Role;

class WhsqSignatureController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = WhsqSignature::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        if (!$query) {
            return $this->message('No signatures found', 404);
        }
        // Filter by whsq_report_id if provided
        if ($request->has('whsq_report_id')) {
            $query->where('whsq_report_id', $request->whsq_report_id);
        }
        // Filter by employee_id if provided
        if ($request->has('employee_id')) {
            $query->where('employee_id', $request->employee_id);
        }
        // Filter by is_site_employee if provided
        if ($request->has('is_site_employee')) {
            $query->where('is_site_employee', $request->is_site_employee);
        }
        $signatures = $query->get();
        return $this->withCount($signatures);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whsq_report_id' => 'nullable|integer',
            'employee_ids' => 'required|array',
            'employee_ids.*' => 'integer',
            'is_site_employee' => 'nullable|boolean',
            'signature' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'job_description' => 'nullable|string',
            'induction_date' => 'nullable|date'
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $employeeIds = $request->employee_ids;
        $createdSignatures = [];
        $ids =  $this->getCustomerAndWorkspaceIds();
        foreach ($employeeIds as $employeeId) {
            $imagePath = null;
            if($request->signature){
                $imagePath = $this->handleFileImageUpload($request, 'whsq_signature')['path'] ?? null;
            }
            $signatureData = [
                'whsq_report_id' => $request->whsq_report_id,
                'customer_id' => $ids['customer_id'],
                'workspace_id' => $ids['workspace_id'],
                'employee_id' => $employeeId,
                'is_site_employee' => $request->is_site_employee ?? 0,
                'signature' => $imagePath,
                'job_description' => $request->job_description,
                'induction_date' => $request->induction_date
            ];
            $signature = WhsqSignature::create($signatureData);
            if ($signature) {
                $createdSignatures[] = $signature;
            }
        }
        if (empty($createdSignatures)) {
            return $this->message('No signatures were created', 400);
        }
        $report = WhsqReport::find($request->whsq_report_id);
        $report->is_completed = 1;
        $report->save();
        $message = count($createdSignatures) . ' signature(s) created successfully';
        return $this->success($createdSignatures, $message);
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $query = WhsqSignature::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $signature = $query->find($id);
        if (!$signature) {
            return $this->message('Signature not found', 404);
        }
        return $this->success($signature);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $query = WhsqSignature::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $signature = $query->find($id);
        if (!$signature) {
            return $this->message('Signature not found', 404);
        }
        $ids =  $this->getCustomerAndWorkspaceIds();
        $imagePath = null;
        $validator = Validator::make($request->all(), [
            'whsq_report_id' => 'nullable|integer',
            'employee_id' => 'nullable|integer',
            'is_site_employee' => 'nullable|boolean',
            'signature' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'job_description' => 'nullable|string',
            'induction_date' => 'nullable|date'
        ]);
        
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        if($request->signature){
            $imagePath = $this->handleFileImageUpload($request, 'whsq_signature',$signature->signature)['path'] ?? null;
        }
        $validatedData = $validator->validated();
        $validatedData['customer_id'] = $ids['customer_id'];
        $validatedData['workspace_id'] = $ids['workspace_id'];
        $validatedData['signature'] = $imagePath;
        $signature->update($validatedData);
        return $this->success($signature, 'Signature updated successfully');
    }

    /**
     * Bulk update signatures for multiple employees
     */
    // public function bulkUpdate(Request $request)
    // {
    //     $validator = Validator::make($request->all(), [
    //         'whsq_report_id' => 'required|integer',
    //         'employee_ids' => 'required|array',
    //         'employee_ids.*' => 'integer',
    //         'is_site_employee' => 'nullable|boolean',
    //         'signature' => 'nullable|string',
    //         'job_description' => 'nullable|string',
    //         'induction_date' => 'nullable|date'
    //     ]);
        
    //     if ($validator->fails()) {
    //         return $this->handleValidationFailure($validator);
    //     }
        
    //     $query = WhsqSignature::query();
    //     $query = $this->applyCustomerWorkspaceFilter($query);
        
    //     $updatedSignatures = [];
    //     $employeeIds = $request->employee_ids;
        
    //     foreach ($employeeIds as $employeeId) {
    //         // Find existing signature for this employee and report
    //         $existingSignature = $query->where('whsq_report_id', $request->whsq_report_id)
    //                                  ->where('employee_id', $employeeId)
    //                                  ->first();
            
    //         if ($existingSignature) {
    //             // Update existing record
    //             $updateData = [
    //                 'is_site_employee' => $request->is_site_employee,
    //                 'signature' => $request->signature,
    //                 'job_description' => $request->job_description,
    //                 'induction_date' => $request->induction_date
    //             ];
                
    //             $existingSignature->update($updateData);
    //             $updatedSignatures[] = $existingSignature;
    //         } else {
    //             // Create new record if doesn't exist
    //             $signatureData = [
    //                 'whsq_report_id' => $request->whsq_report_id,
    //                 'employee_id' => $employeeId,
    //                 'is_site_employee' => $request->is_site_employee,
    //                 'signature' => $request->signature,
    //                 'job_description' => $request->job_description,
    //                 'induction_date' => $request->induction_date
    //             ];
                
    //             $newSignature = WhsqSignature::create($signatureData);
    //             if ($newSignature) {
    //                 $updatedSignatures[] = $newSignature;
    //             }
    //         }
    //     }
        
    //     if (empty($updatedSignatures)) {
    //         return $this->message('No signatures were updated or created', 400);
    //     }
        
    //     $message = count($updatedSignatures) . ' signature(s) processed successfully';
    //     return $this->success($updatedSignatures, $message);
    // }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $query = WhsqSignature::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $signature = $query->find($id);
        if (!$signature) {
            return $this->message('Signature not found', 404);
        }
        $signature->delete();
        return $this->message('Signature deleted successfully');
    }
    /**
     * Get signatures by WHSQ report ID
     */
    public function getByReport($reportId)
    {   
        $report = WhsqReport::query();
        $ids = $this->getCustomerAndWorkspaceIds();
        $report = $this->applyCustomerWorkspaceFilter($report);
        $report = $report->with(['authoriseBy','signatures'=>function($query) use ($ids, $reportId){
            $query->where('customer_id', $ids['customer_id'])
                ->where('workspace_id', $ids['workspace_id'])
                ->where('whsq_report_id', $reportId);
        }])->find($reportId);
        $baseModel = new \App\Models\BaseModel();
        $userDateFormat = $baseModel->getUserDateFormat();
        // Add role information to each signature
        if(isset($report->signatures)){
        foreach ($report->signatures as $signature) {
            if ($signature->employee_id) {
                // Get role title based on employee_type (role code) - roles are now global
                $role_code = EmpCompanyDetails::where('id', $signature->employee_id)->first()->access_role;
                $role = Role::where('code', $role_code)
                    ->where('del', '0')
                    ->first();
                
                $signature->setAttribute('role_title', $role ? $role->title : null);
            } else {
                    $signature->setAttribute('role_title', null);
                }
            if (empty($signature->induction_date) || !isset($signature->induction_date) || $signature->induction_date === null) {
                if (isset($signature->created_at) && $signature->created_at) {
                    try {
                        $createdAtDate = \Carbon\Carbon::parse($signature->created_at);
                        $signature->setAttribute('induction_date', $createdAtDate->format($userDateFormat));
                    } catch (\Exception $e) {
                        // If parsing fails, use current date as fallback
                        $signature->setAttribute('induction_date', now()->format($userDateFormat));
                    }
                } else {
                    // If no created_at, use current date
                    $signature->setAttribute('induction_date', now()->format($userDateFormat));
                    }
                }
            }
        }
        $reportSignatures = collect($report->signatures);

        // Check if authorised_by employee is already in the signature data
        $authorisedByInSignatures = $reportSignatures->contains('employee_id', $report->authorised_by);
        // If authorised_by is not in signatures table and not 0 (customer), add them with null signature
        if (!$authorisedByInSignatures && $report->authorised_by && $report->authorised_by != 0) {
            // Fetch authorised_by employee details
            $authorisedByDetails = DB::table(table: 'emp_personal_details')
                ->leftJoin('emp_company_details', 'emp_personal_details.emp_id', '=', 'emp_company_details.id')
                ->leftJoin('roles', 'emp_company_details.access_role', '=', 'roles.code')
                ->where('emp_personal_details.emp_id', $report->authorised_by)
                ->where('emp_personal_details.del', '0')
                ->where('emp_company_details.status', '1')
                ->where('emp_company_details.approved', '1')
                ->where('emp_company_details.compeleted', '1')
                ->where('emp_company_details.customer_id', $report->customer_id)
                ->where('emp_company_details.workspace_id', operator: $report->workspace_id)
                ->where('roles.del', '0')
                ->select(
                    'emp_personal_details.emp_id',
                    'emp_personal_details.first_name',
                    'emp_personal_details.middle_name',
                    'emp_personal_details.last_name',
                    'emp_company_details.access_role',
                    'roles.title as role_title'
                )->first();

            if ($authorisedByDetails) {
                // Create complete array structure for authorised_by to match existing signature format
                $authorisedBySignatureArray = [
                    'id' => $authorisedByDetails->emp_id,
                    'whsq_report_id' => $report->id,
                    'itpc_id' => null,
                    'employee_id' => (string) $report->authorised_by,
                    'employee_name' => trim(($authorisedByDetails->first_name ?? '') . ' ' .
                                      ($authorisedByDetails->middle_name ?? '') . ' ' .
                                      ($authorisedByDetails->last_name ?? '')),
                    'employee_type' => $authorisedByDetails->access_role,
                    'signature' => null, // Null indicates signature is required
                    'signature_type' => null,
                    'date' => $report->issue_date,
                    'time' => null,
                    'induction_date' => now()->format($userDateFormat),
                    'del' => '0',
                    'created_at' => null,
                    'updated_at' => null,
                    'role_title' => $authorisedByDetails->role_title,
                    'employee' => [
                        'emp_id' => (string) $authorisedByDetails->emp_id,
                        'first_name' => $authorisedByDetails->first_name,
                        'middle_name' => $authorisedByDetails->middle_name,
                        'last_name' => $authorisedByDetails->last_name,
                    ]
                ];

                // Add to signature collection
                $report->signatures->push((object) $authorisedBySignatureArray);
            }
        }
        if(!$report){
            return $this->message('Report not found', 404);
        }
        return $this->success($report);
    }
    /**
     * Get signatures by employee ID
     */
    public function getByEmployee($employeeId)
    {
        $query = WhsqSignature::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $signatures = $query->where('employee_id', $employeeId)->get();

        return $this->success($signatures);
    }
}
