<?php

namespace App\Http\Controllers;

use App\Models\DocumentType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DocumentTypeController extends Controller
{
    /**
     * Display a listing of document types.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(DocumentType $documentType, Request $request)
    {
        $documentTypes = $documentType->latest('id')->where('del', '0');
        
        // Add search functionality if search parameter is provided
        if ($request->filled('search')) {
            $search = $request->input('search');
            $documentTypes->where('title', 'like', '%' . $search . '%');
        }
        
        return $this->withCount($documentTypes, "Document types retrieved successfully.");
    }

    /**
     * Store a newly created document type in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = $this->documentTypeValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        $validatedData = $validator->validated();
        
        // Check if document type with same title already exists
        $existingDocumentType = DocumentType::where('title', $validatedData['title'])
            ->where('del', '0')
            ->first();
            
        if ($existingDocumentType) {
            return $this->error('Document type with this title already exists', 422);
        }

        // Set default del value if not provided
        if (!isset($validatedData['del'])) {
            $validatedData['del'] = '0';
        }

        $documentType = DocumentType::create($validatedData);

        return $this->success($documentType, 'Document type created successfully', 201);
    }

    /**
     * Display the specified document type.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $documentType = DocumentType::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$documentType) {
            return $this->notFound('Document type not found', 404);
        }

        return $this->success($documentType, 'Document type retrieved successfully');
    }

    /**
     * Update the specified document type in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validator = $this->documentTypeValidationRequest($request, true);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        $validatedData = $validator->validated();
        $id = $request->input('id');

        if (!$id) {
            return $this->error('Document type ID is required', 422);
        }

        $documentType = DocumentType::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$documentType) {
            return $this->notFound('Document type not found', 404);
        }

        // Check if another document type with same title already exists (excluding current one)
        if (isset($validatedData['title'])) {
            $existingDocumentType = DocumentType::where('title', $validatedData['title'])
                ->where('id', '!=', $id)
                ->where('del', '0')
                ->first();
                
            if ($existingDocumentType) {
                return $this->error('Document type with this title already exists', 422);
            }
        }

        $documentType->update($validatedData);

        return $this->success($documentType->fresh(), 'Document type updated successfully');
    }

    /**
     * Remove the specified document type from storage (soft delete).
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $documentType = DocumentType::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$documentType) {
            return $this->notFound('Document type not found', 404);
        }

        // Check if document type is being used by any site documents
        if ($documentType->siteDocuments()->count() > 0) {
            return $this->error('Cannot delete document type. It is being used by site documents.', 422);
        }

        // Soft delete by setting del to '1'
        $documentType->update(['del' => '1']);

        return $this->message('Document type deleted successfully', 200);
    }
}

