<?php

namespace App\Http\Controllers;

use App\Models\EmpCompanyDetails;
use DB;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\RequiredDocument;
use App\Models\EmpPersonalDetails;
use Illuminate\Support\Facades\Auth;
use App\Models\RequiredDocumentField;
use Illuminate\Support\Facades\Validator;

class RequiredDocumentController extends Controller
{
    public function index(Request $request)
{
    $userTable = $this->getUserTable();
    $query = RequiredDocument::query()->with('requiredDocumentField')->latest('id'); // Eager load the relationship

    if ($userTable === "customer") {
        $query->where('del', '0')
              ->where('customer_id', auth()->id())
              ->where('workspace_id', auth()->user()->current_workspace_id);
    }

    if ($userTable === "emp") {
        $query->where('del', '0')
              ->where('customer_id', auth()->user()->customer_id) // Assuming customer_id links employee to projects
              ->where('workspace_id', auth()->user()->workspace_id);
    }
    
    // Handle for_who filtering based on emp_id parameter
    if ($request->has('emp_id')) {
        // Check if the provided emp_id is internal or external
        $employee = EmpCompanyDetails::withoutGlobalScopes()->find($request->emp_id);
        
        if (!$employee) {
            return $this->error('Employee not found', 404);
        }
        
        // Check if the employee belongs to the current user's workspace
        if ($userTable === "customer") {
            if ($employee->customer_id != auth()->id() || $employee->workspace_id != auth()->user()->current_workspace_id) {
                return $this->error('You do not have access to this employee', 403);
            }
        } elseif ($userTable === "emp") {
            if ($employee->customer_id != auth()->user()->customer_id || $employee->workspace_id != auth()->user()->workspace_id) {
                return $this->error('You do not have access to this employee', 403);
            }
        }
        
        $isInternal = ($employee->user_type === '0' || $employee->user_type === 0); // 0 = Internal, 1 = External
        $isExternal = ($employee->user_type === '1' || $employee->user_type === 1); // 1 = External
        
        if ($isInternal) {
            // For internal employees, return documents with for_who = 'internal' or 'both'
            $query->where(function($q) {
                $q->where('for_who', 'internal')
                  ->orWhere('for_who', 'both');
            });
        } elseif ($isExternal) {
            // For external employees, return documents with for_who = 'external' or 'both'
            $query->where(function($q) {
                $q->where('for_who', 'external')
                  ->orWhere('for_who', 'both');
            });
        } else {
            // If no conditions match (unknown user_type), return only 'both' documents
            $query->where('for_who', 'both');
        }
    }
    
    // Apply search filter
    if ($request->filled('search')) {
        $searchTerm = $request->search;
        $query->where(function ($q) use ($searchTerm) {
            $q->where('title', 'like', '%' . $searchTerm . '%')
              ->orWhereHas('requiredDocumentField', function ($subquery) use ($searchTerm) {
                  $subquery->where('field_name', 'like', '%' . $searchTerm . '%');
              });
        });
    }
    
    $required_documents = $query->get();

    return $this->success($required_documents, 'Required Documents Get Successfully');
}

    public function store(Request $request)
    {
     
        $user = auth()->user();

        $validator = Validator::make($request->all(), [
            'title'      => 'required',
            'for_who'    => 'required',
            'field_name' => 'required|array',
            'field_type' => 'required|array',
            'field_required' => 'required|array',
            'priority' => 'required|array',
        ]);

        if ($validator->fails()) {

            $error = $validator->errors()->first();

            return $this->error($error,422);

        } else {

            $validatedData =  $validator->validated();

            $RequiredDocumentData = [
                'title'   =>  $validatedData['title'],
                'for_who' =>  $validatedData['for_who']
            ];

            $userTable = $this->getUserTable();
            $auth_id =0;
            $workspace_id = 0;
            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;  
                $authPersonalDetails = User::where('id', Auth::user()->id)->first();  
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
                $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
            }
            $RequiredDocumentData['customer_id'] = $auth_id;
            $RequiredDocumentData['workspace_id'] = $workspace_id;

           $insertGetId =  RequiredDocument::insertGetId($RequiredDocumentData);

           $RequiredDocumentDataArr = [];

            $i = 0;
           foreach ($validatedData['field_name'] as $key => $value)
           { 
                $RequiredDocumentDataArr[$i] = [
                    'field_type' => $validatedData['field_type'][$key],
                    'field_name' => $validatedData['field_name'][$key],
                    'doc_id'     => $insertGetId,
                    'field_required' => $validatedData['field_required'][$key],
                    'priority' => $validatedData['priority'][$key]
                ];

                $i++;
           }

           RequiredDocumentField::insert($RequiredDocumentDataArr);

           $required_documents =  RequiredDocument::where('customer_id', $auth_id)
                                                    ->where('workspace_id', $workspace_id)
                                                    ->where('del','0')->get();

           $data['required_documents'] = $required_documents;
           return $this->success($data, 'Required Documents Store Successfully');
        }
    }

    public function document_edit(Request $request)
    {
        $id=$request->id;
        $userTable = $this->getUserTable();
        $required_documents = RequiredDocument::find($id);
        if (
            $userTable == "customer" && ($required_documents->workspace_id != auth()->user()->current_workspace_id || $required_documents->customer_id != auth()->user()->id)
        ) {
            return $this->message('You do not have access to this Employee Requird Document', 403);
        }

        if ($userTable == "emp" && ($required_documents->customer_id != auth()->user()->customer_id || $required_documents->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Employee Requird Document', 403);
        }
        return $this->success($required_documents, 'Get Employee Requird Document Details Successfully');
    }

    public function update(Request $request)
    {
        $user = auth()->user();
        $validator = Validator::make($request->all(), [
            'title'      => 'required',
            'for_who'    => 'required',
            'document_id'    => 'required',
            'field_name' => 'required|array',
            'field_type' => 'required|array',
            'field_required' => 'required|array',
            'status' => 'required|array',
            'has_data' => 'required|array',
            'id_list' => 'required|array',
            'priority' => 'required|array',
            ]);
        
        if ($validator->fails()) {
            
            $errors = $validator->errors()->first();
            return $this->error($errors,422);

        } else {
          
            $validatedData =  $validator->validated();
            
            // Check if all arrays have the same length as field_name
            $fieldCount = count($validatedData['field_name']);
            $arrayFields = ['field_type', 'field_required', 'status', 'has_data', 'id_list', 'priority'];
            
            foreach ($arrayFields as $field) {
                if (count($validatedData[$field]) !== $fieldCount) {
                    return $this->error("Array length mismatch: {$field} must have the same number of elements as field_name", 422);
                }
            }
            
            $document = RequiredDocument::where('id', $validatedData['document_id'])->first();
            $userTable = $this->getUserTable();
        
            if ($userTable == "customer" && ($document->workspace_id != auth()->user()->current_workspace_id || $document->customer_id != auth()->user()->id)
            ) {
                return $this->message('You do not have access to this document', 403);
            }

            if ($userTable == "emp" && ($document->customer_id != auth()->user()->customer_id || $document->workspace_id != auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this document', 403);
            }
            if (!$document) {
                return $this->notFound('document Not Found', 404);
            }

            RequiredDocument::where('id', $validatedData['document_id'])
            ->update([
                'title' => $validatedData['title'],
                'for_who' => $validatedData['for_who']
            ]);
            $RequiredDocumentDataArr = [];

            $i = 0;
            foreach ($validatedData['field_name'] as $key => $value)
            {
                // Safety check: ensure all required array keys exist (allow null for id_list)
                if (!array_key_exists($key, $validatedData['id_list']) || 
                    !isset($validatedData['has_data'][$key]) || 
                    !isset($validatedData['field_type'][$key]) ||
                    !isset($validatedData['field_required'][$key]) ||
                    !isset($validatedData['status'][$key]) ||
                    !isset($validatedData['priority'][$key])) {
                    continue; // Skip this iteration if any required data is missing
                }
                
                // Check if this is a new field (null or 0 in id_list)
                if($validatedData['id_list'][$key] === null || $validatedData['id_list'][$key] == 0)
                {
                    $RequiredDocumentDataArr= [
                        'field_type' => $validatedData['field_type'][$key],
                        'field_name' => $validatedData['field_name'][$key],
                        'doc_id'     => $validatedData['document_id'],
                        'field_required' => $validatedData['field_required'][$key],
                        'status' => $validatedData['status'][$key],
                        'priority' => $validatedData['priority'][$key]
                    ];
                    
                    // Log new field creation for debugging
                    \Log::info('Creating new required document field', [
                        'field_name' => $validatedData['field_name'][$key],
                        'field_type' => $validatedData['field_type'][$key],
                        'doc_id' => $validatedData['document_id']
                    ]);
                    
                    RequiredDocumentField::create($RequiredDocumentDataArr);

                }
                else
                {
                    // Update existing field
                    $RequiredDocumentDataArr= [
                        'field_type' => $validatedData['field_type'][$key],
                        'field_name' => $validatedData['field_name'][$key],
                        'doc_id'     => $validatedData['document_id'],
                        'field_required' => $validatedData['field_required'][$key],
                        'status' => $validatedData['status'][$key],
                        'priority' => $validatedData['priority'][$key]
                    ];
                    RequiredDocumentField::where(['id' => $validatedData['id_list'][$key]])->update($RequiredDocumentDataArr);
                    RequiredDocumentField::where('doc_id', $validatedData['document_id'])->whereNotIn('id', $validatedData['id_list'])->delete();
                }
                $i++;
            }
 
            $userTable = $this->getUserTable();
            $auth_id =0;
            $workspace_id = 0;
            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;  
                $authPersonalDetails = User::where('id', Auth::user()->id)->first(); 
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
                $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
            }
            

            $required_documents =  RequiredDocument::where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->where('del','0')->get();

            $data['required_documents'] = $required_documents;
           
            return $this->success($data, 'Required Documents Updated Successfully');   
        }        

    }

    public function document_delete(Request $request)
    {
        $id=$request->id;
        $userTable = $this->getUserTable();
        $document = RequiredDocument::find($id);
    
        if ($userTable == "customer" && ($document->workspace_id != auth()->user()->current_workspace_id || $document->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Document', 403);
        }

        if ($userTable == "emp" && ($document->customer_id != auth()->user()->customer_id || $document->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Document', 403);
          
        }
        $document->del='1';
        $document->save();
         
        $user = auth()->user();
            if($userTable == "customer"){
                    $data['document'] = RequiredDocument::where('customer_id', $user->id)
                    ->where('workspace_id', $user->current_workspace_id)
                    ->where('del', '0')
                    ->get();
                }
                elseif($userTable == "emp"){
                    $data['document'] = RequiredDocument::where('customer_id',auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id)
                    ->where('del', '0')
                    ->get();
                }

        return $this->success($data, 'Required Documents Deleted Successfully');   
    }


    public function delete_field(Request $request)
    {
        RequiredDocumentField::where('id', $request->id)->delete();
       
        return $this->message('Field Deleted Successfully');   
    }

  
}
