<?php

namespace Modules\SystemCore\App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Modules\SystemCore\App\Http\Requests\StoreCustomerDocumentRequest;
use Modules\SystemCore\App\Http\Requests\UpdateCustomerDocumentRequest;
use Modules\SystemCore\App\Models\CoreCustomer;
use Modules\SystemCore\App\Models\CustomerDocument;

class CustomerDocumentController extends Controller
{
    /**
     * Store a newly created customer document in storage.
     */
    public function store(StoreCustomerDocumentRequest $request, CoreCustomer $customer)
    {
        $validatedData = $request->validated();

        // Handle file upload
        if ($request->hasFile('document_file')) {
            $file = $request->file('document_file');
            $path = $file->store("customer-documents/{$customer->id}", 'public');

            $validatedData['customer_id'] = $customer->id;
            $validatedData['file_path'] = $path;
            $validatedData['file_name'] = $file->getClientOriginalName();
            $validatedData['mime_type'] = $file->getMimeType();
            $validatedData['file_size'] = $file->getSize();
        }

        // Remove the document_file from validated data as we've processed it
        unset($validatedData['document_file']);

        $document = CustomerDocument::create($validatedData);

        return response()->json([
            'success' => true,
            'message' => __('Document uploaded successfully.'),
            'data' => $document,
        ]);
    }

    /**
     * Display the specified customer document for editing.
     */
    public function show(CoreCustomer $customer, CustomerDocument $document)
    {
        // Ensure the document belongs to the customer
        if ($document->customer_id !== $customer->id) {
            return response()->json([
                'success' => false,
                'message' => __('Document not found.'),
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $document->id,
                'document_title' => $document->document_title,
                'document_number' => $document->document_number,
                'document_type' => $document->document_type,
                'file_name' => $document->file_name,
                'file_url' => $document->file_url,
                'mime_type' => $document->mime_type,
                'file_size' => $document->file_size,
                'formatted_file_size' => $document->formatted_file_size,
                'issue_date' => $document->issue_date?->format('Y-m-d'),
                'expiry_date' => $document->expiry_date?->format('Y-m-d'),
                'notes' => $document->notes,
                'is_active' => $document->is_active,
                'is_expired' => $document->isExpired(),
            ],
        ]);
    }

    /**
     * Update the specified customer document in storage.
     */
    public function update(UpdateCustomerDocumentRequest $request, CoreCustomer $customer, CustomerDocument $document)
    {
        // Ensure the document belongs to the customer
        if ($document->customer_id !== $customer->id) {
            return response()->json([
                'success' => false,
                'message' => __('Document not found.'),
            ], 404);
        }

        $validatedData = $request->validated();

        // Handle file upload if a new file is provided
        if ($request->hasFile('document_file')) {
            // Delete old file if it exists
            if ($document->file_path) {
                Storage::disk('public')->delete($document->file_path);
            }

            $file = $request->file('document_file');
            $path = $file->store("customer-documents/{$customer->id}", 'public');

            $validatedData['file_path'] = $path;
            $validatedData['file_name'] = $file->getClientOriginalName();
            $validatedData['mime_type'] = $file->getMimeType();
            $validatedData['file_size'] = $file->getSize();
        }

        // Remove the document_file from validated data as we've processed it
        unset($validatedData['document_file']);

        $document->update($validatedData);

        return response()->json([
            'success' => true,
            'message' => __('Document updated successfully.'),
            'data' => $document->fresh(),
        ]);
    }

    /**
     * Remove the specified customer document from storage.
     */
    public function destroy(CoreCustomer $customer, CustomerDocument $document)
    {
        // Ensure the document belongs to the customer
        if ($document->customer_id !== $customer->id) {
            return response()->json([
                'success' => false,
                'message' => __('Document not found.'),
            ], 404);
        }

        // Delete the file from storage
        if ($document->file_path) {
            Storage::disk('public')->delete($document->file_path);
        }

        // Delete the document record
        $document->delete();

        return response()->json([
            'success' => true,
            'message' => __('Document deleted successfully.'),
        ]);
    }

    /**
     * Download the specified customer document.
     */
    public function download(CoreCustomer $customer, CustomerDocument $document)
    {
        // Ensure the document belongs to the customer
        if ($document->customer_id !== $customer->id) {
            return back()->with('error', __('Document not found.'));
        }

        if (! $document->file_path || ! Storage::disk('public')->exists($document->file_path)) {
            return back()->with('error', __('Document file not found.'));
        }

        // Build filename for download
        $fileName = str_replace(' ', '_', $document->document_title);
        if ($document->document_number) {
            $fileName .= "_{$document->document_number}";
        }

        // Determine file extension
        $extension = pathinfo($document->file_path, PATHINFO_EXTENSION);
        if (! $extension) {
            // Default based on mime type if extension isn't in the path
            $extension = match ($document->mime_type) {
                'application/pdf' => 'pdf',
                'image/jpeg' => 'jpg',
                'image/png' => 'png',
                'application/msword' => 'doc',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
                default => 'pdf',
            };
        }

        $fileName .= '.'.$extension;

        return Storage::disk('public')->download($document->file_path, $fileName);
    }
}
