<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../../helpers/validation.php';
require_once __DIR__ . '/../../../Middleware/VendorAuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class DocumentController
{

    public function index()
    {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];

        $db = Database::getInstance();

        // Auto-detect and update expired documents
        $db->query("
            UPDATE vendor_documents 
            SET status = 'expired' 
            WHERE expiry_date IS NOT NULL 
              AND expiry_date < CURRENT_DATE() 
              AND status != 'expired'
        ");

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $totalStmt = $db->prepare("SELECT COUNT(*) FROM vendor_documents WHERE vendor_id = ?");
        $totalStmt->execute([$vendorId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT vd.*, dt.name_en as document_type_name
            FROM vendor_documents vd
            JOIN document_types dt ON vd.document_type_id = dt.id
            WHERE vd.vendor_id = ?
            ORDER BY dt.name_en ASC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$vendorId]);
        $documents = $stmt->fetchAll();

        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Documents loaded successfully', ['documents' => $documents], $pagination);
    }

    public function upload()
    {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];

        $documentTypeId = $_POST['document_type_id'] ?? null;
        $expiryDate = $_POST['expiry_date'] ?? null;

        if (!$documentTypeId || !isset($_FILES['document'])) {
            sendError('Document type and file are required', [], 422);
        }

        $file = $_FILES['document'];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            sendError('File upload failed', ['error_code' => $file['error']], 400);
        }

        $db = Database::getInstance();

        // Check if a document of this type already exists for the vendor
        $stmtExist = $db->prepare("SELECT id, status FROM vendor_documents WHERE vendor_id = ? AND document_type_id = ? LIMIT 1");
        $stmtExist->execute([$vendorId, $documentTypeId]);
        $existing = $stmtExist->fetch();

        if ($existing && $existing['status'] === 'pending') {
            sendError('Document is currently under review by our compliance team. You cannot replace it while pending.', [], 400);
        }

        $uploadDir = __DIR__ . '/../../../../public/uploads/vendors/documents/';
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid('doc_' . $vendorId . '_') . '.' . $ext;

        if (move_uploaded_file($file['tmp_name'], $uploadDir . $filename)) {
            $filePath = '/public/uploads/vendors/documents/' . $filename;

            if ($existing) {
                $stmt = $db->prepare("
                    UPDATE vendor_documents 
                    SET file_path = ?, expiry_date = ?, status = 'pending', created_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$filePath, $expiryDate ?: null, $existing['id']]);
            } else {
                $stmt = $db->prepare("
                    INSERT INTO vendor_documents (vendor_id, document_type_id, file_path, expiry_date, status, created_at)
                    VALUES (?, ?, ?, ?, 'pending', NOW())
                ");
                $stmt->execute([$vendorId, $documentTypeId, $filePath, $expiryDate ?: null]);
            }

            sendResponse(['file_path' => $filePath], 'Document uploaded successfully', 201);
        } else {
            sendError('Failed to save file', [], 500);
        }
    }
}
