<?php
declare(strict_types=1);

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../config/auth.php";

require_admin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: verifications.php");
    exit;
}

$visit_id = (int)($_POST["visit_id"] ?? 0);
$action = $_POST["action"] ?? "";
$remarks = trim($_POST["remarks"] ?? "");
$csrf_token = $_POST["csrf_token"] ?? "";

// Verify CSRF token
if (!csrf_validate($csrf_token)) {
    $_SESSION["error"] = "Invalid security token";
    header("Location: verifications.php");
    exit;
}

if (!$visit_id || !in_array($action, ["approve", "reject"])) {
    $_SESSION["error"] = "Invalid request";
    header("Location: verifications.php");
    exit;
}

$status = $action === "approve" ? "APPROVED" : "REJECTED";
$admin_id = (int)($_SESSION["user_id"] ?? 0);

try {
    $stmt = $pdo->prepare('
        UPDATE school_visits 
        SET verification_status = ?, 
            verification_verified_at = NOW(), 
            verification_verified_by = ?, 
            verification_admin_remark = CONCAT(IFNULL(verification_admin_remark, ""), ?)
        WHERE id = ? AND verification_status = ?
    ');
    $remarks_text = $remarks ? "\nAdmin remarks: " . $remarks : "";
    $stmt->execute([$status, $admin_id, $remarks_text, $visit_id, 'PENDING']);
    
    if ($stmt->rowCount() > 0) {
        $_SESSION["success"] = "Verification " . strtolower($status) . " successfully";
        
        // If approved, maybe update school status or send notification
        if ($status === "APPROVED") {
            // Get school_id for this visit
            $school_stmt = $pdo->prepare("SELECT school_id FROM school_visits WHERE id = ?");
            $school_stmt->execute([$visit_id]);
            $school_id = $school_stmt->fetchColumn();
            
            // You can add additional logic here when school is verified
            // e.g., update school status, send notification to rep, etc.
        }
    } else {
        $_SESSION["error"] = "Verification request not found or already processed";
    }
} catch (PDOException $e) {
    $_SESSION["error"] = "Database error occurred";
    error_log($e->getMessage());
}

header("Location: verifications.php");
exit;
