<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized Access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid Request Method']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true) ?? $_POST;

$doc_id = $data['doc_id'] ?? 0;
$action = $data['action'] ?? ''; // 'Approve', 'Reject', 'Correction'
$remarks = trim($data['remarks'] ?? '');

if (!$doc_id || !in_array($action, ['Approve', 'Reject', 'Correction'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid document ID or action']);
    exit;
}

$db = getDB();

// Determine status based on action
$status = 'Under Review';
if ($action === 'Approve') $status = 'Verified';
if ($action === 'Reject') $status = 'Rejected';
if ($action === 'Correction') $status = 'Correction Needed';

try {
    $db->beginTransaction();

    // Update Document Status
    $stmt = $db->prepare("UPDATE employee_documents SET status = ?, remarks = ? WHERE doc_id = ?");
    $stmt->execute([$status, $remarks, $doc_id]);

    // Insert Verification Log
    $log = $db->prepare("INSERT INTO verification_logs (doc_id, verified_by, action, comments) VALUES (?, ?, ?, ?)");
    $log->execute([$doc_id, $_SESSION['admin_id'], $action, $remarks]);

    // Optional: Re-calculate total employee verification status
    // Get employee_id
    $emp_stmt = $db->prepare("SELECT employee_id FROM employee_documents WHERE doc_id = ?");
    $emp_stmt->execute([$doc_id]);
    $emp = $emp_stmt->fetch();
    
    if ($emp) {
        // If all docs are Verified, set employee status to Verified
        $check = $db->prepare("SELECT count(*) as pending_count FROM employee_documents WHERE employee_id = ? AND status != 'Verified'");
        $check->execute([$emp['employee_id']]);
        $pending = $check->fetch()['pending_count'];
        
        $new_emp_status = 'Under Review';
        if ($pending == 0) $new_emp_status = 'Verified';
        if ($status === 'Correction Needed' || $status === 'Rejected') $new_emp_status = 'Correction Needed';
        
        $db->prepare("UPDATE employees SET verification_status = ? WHERE id = ?")->execute([$new_emp_status, $emp['employee_id']]);
    }

    $db->commit();
    echo json_encode(['success' => true, 'message' => 'Document ' . strtolower($action) . 'd successfully.', 'new_status' => $status]);

} catch (Exception $e) {
    $db->rollBack();
    echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
}
