<?php
require_once __DIR__ . '/../../../Models/VendorDocument.php';
require_once __DIR__ . '/../../../Models/Database.php';

class VendorDocumentController {
    public function index() {
        $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['p']) ? (int)$_GET['p'] : 1;
        $perPage = 10;
        $offset = ($page - 1) * $perPage;
        
        $vendorId = isset($_GET['vendor_id']) && $_GET['vendor_id'] !== '' ? (int)$_GET['vendor_id'] : null;
        
        if ($vendorId) {
            $total = 1;
            $totalPages = 1;
            
            $vendorsStmt = $db->prepare("
                SELECT id, agency_name, email
                FROM vendors
                WHERE id = ?
            ");
            $vendorsStmt->execute([$vendorId]);
            $vendors = $vendorsStmt->fetchAll();
        } else {
            $countStmt = $db->query("SELECT COUNT(DISTINCT vendor_id) FROM vendor_documents");
            $total = $countStmt->fetchColumn();
            $totalPages = ceil($total / $perPage);
            
            $vendorsStmt = $db->prepare("
                SELECT DISTINCT v.id, v.agency_name, v.email
                FROM vendors v
                JOIN vendor_documents vd ON v.id = vd.vendor_id
                ORDER BY v.agency_name ASC
                LIMIT ? OFFSET ?
            ");
            $vendorsStmt->bindValue(1, $perPage, PDO::PARAM_INT);
            $vendorsStmt->bindValue(2, $offset, PDO::PARAM_INT);
            $vendorsStmt->execute();
            $vendors = $vendorsStmt->fetchAll();
        }
        
        foreach ($vendors as &$vendor) {
            $docStmt = $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
            ");
            $docStmt->execute([$vendor['id']]);
            $vendor['documents'] = $docStmt->fetchAll();
            
            $hasPending = false;
            foreach ($vendor['documents'] as $doc) {
                if ($doc['status'] === 'pending') {
                    $hasPending = true;
                    break;
                }
            }
            $vendor['has_pending'] = $hasPending;
        }
        
        require __DIR__ . '/../../../../views/admin/vendor_documents/index.php';
    }

    public function approve() {
        $id = $_GET['id'] ?? 0;
        $documentModel = new VendorDocument();
        $documentModel->update($id, [
            'status' => 'approved',
            'reviewed_at' => date('Y-m-d H:i:s')
        ]);
        header("Location: ?page=vendor_documents&success=Document approved");
    }

    public function reject() {
        $id = $_POST['id'] ?? 0;
        $note = $_POST['admin_note'] ?? '';
        $documentModel = new VendorDocument();
        $documentModel->update($id, [
            'status' => 'rejected',
            'admin_note' => $note,
            'reviewed_at' => date('Y-m-d H:i:s')
        ]);
        header("Location: ?page=vendor_documents&success=Document rejected");
    }

    public function updateExpiry() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header("Location: ?page=vendor_documents&error=Invalid request method");
            exit;
        }
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $expiryDate = $_POST['expiry_date'] ?? '';
        
        if (empty($id) || empty($expiryDate)) {
            header("Location: ?page=vendor_documents&error=Missing document ID or expiry date");
            exit;
        }

        $documentModel = new VendorDocument();
        $documentModel->update($id, [
            'expiry_date' => $expiryDate
        ]);

        header("Location: ?page=vendor_documents&success=Expiry date updated successfully");
        exit;
    }
}
