<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\CustomerDocument;
use App\Models\DocumentType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class CustomerDocumentVaultController extends Controller
{
    public function index(Request $request)
    {
        $tenantId = $request->user()->tenant_id;
        $baseQuery = CustomerDocument::where('tenant_id', $tenantId)->where('is_current', true);
        $today = today();
        $warningDate = today()->addDays(60);
        $metrics = [
            'total' => (clone $baseQuery)->count(),
            'valid' => (clone $baseQuery)->where(fn ($q) => $q->whereNull('expiry_date')->orWhere('expiry_date', '>', $warningDate))->count(),
            'expiring' => (clone $baseQuery)->whereBetween('expiry_date', [$today, $warningDate])->count(),
            'expired' => (clone $baseQuery)->whereDate('expiry_date', '<', $today)->count(),
        ];

        $documents = $baseQuery
            ->with(['customer.contact', 'documentType'])
            ->when($request->filled('q'), function ($query) use ($request) {
                $term = '%'.$request->string('q').'%';
                $query->where(function ($q) use ($term) {
                    $q->where('document_name', 'like', $term)
                        ->orWhere('document_number', 'like', $term)
                        ->orWhereHas('customer', fn ($customer) => $customer->where('full_name_en', 'like', $term)->orWhere('customer_code', 'like', $term));
                });
            })
            ->when($request->input('expiry') === 'valid', fn ($q) => $q->where(fn ($inner) => $inner->whereNull('expiry_date')->orWhere('expiry_date', '>', $warningDate)))
            ->when($request->input('expiry') === 'expiring', fn ($q) => $q->whereBetween('expiry_date', [$today, $warningDate]))
            ->when($request->input('expiry') === 'expired', fn ($q) => $q->whereDate('expiry_date', '<', $today))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('tenant.customers.documents.index', compact('documents', 'metrics'));
    }

    public function download(int $id)
    {
        $document = CustomerDocument::where('tenant_id', auth()->user()->tenant_id)->findOrFail($id);
        abort_unless($document->attachment_path && Storage::disk('local')->exists($document->attachment_path), 404);
        $extension = pathinfo($document->attachment_path, PATHINFO_EXTENSION);
        $filename = Str::slug($document->document_name ?: 'customer-document').($extension ? ".{$extension}" : '');

        return Storage::disk('local')->download($document->attachment_path, $filename);
    }

    public function store(Request $request, $customerId)
    {
        $request->validate([
            'document_name' => 'required|string|max:180',
            'attachment' => 'required|file|mimes:pdf,jpg,jpeg,png,webp|max:10240',
            'issue_date' => 'nullable|date',
            'expiry_date' => 'nullable|date|after_or_equal:issue_date',
        ]);

        $tenant = $request->user()->tenant;
        $customer = Customer::where('tenant_id', $tenant->id)->findOrFail($customerId);
        $documentTypeId = null;
        if ($request->filled('document_type_id')) {
            $documentTypeId = DocumentType::where('tenant_id', $tenant->id)->findOrFail($request->integer('document_type_id'))->id;
        }
        $path = $request->file('attachment')->store("tenants/{$tenant->uuid}/customers/{$customer->uuid}/documents", 'local');
        $document = CustomerDocument::create([
            'tenant_id' => $tenant->id,
            'customer_id' => $customer->id,
            'document_type_id' => $documentTypeId,
            'document_number' => $request->document_number,
            'document_name' => $request->document_name,
            'issue_date' => $request->issue_date,
            'expiry_date' => $request->expiry_date,
            'attachment_path' => $path,
            'status' => 'valid',
            'version' => 1,
            'is_current' => true,
        ]);

        return back()->with('status', "Document {$document->document_name} uploaded securely to the vault.");
    }
}
