<?php
require_once __DIR__ . '/../../../Models/MaidDocument.php';

class MaidDocumentController {
    public function index() {
        $documentModel = new MaidDocument();
        
        // Auto-detect and update expired documents
        $db = Database::getInstance();
        $db->query("
            UPDATE maid_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;
        
        $result = $documentModel->paginateWithDetails($page, $perPage);
        $documents = $result['data'];
        
        $total = $result['total'];
        $totalPages = ceil($total / $perPage);

        require __DIR__ . '/../../../../views/admin/maid_documents/index.php';
    }

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

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