<?php
require_once __DIR__ . '/includes/expense_common.php';
expense_require_role(['admin','superadmin','manager']);
expense_ensure_schema($conn);

$manager_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !expense_csrf_valid()) {
    set_flash('danger', 'Invalid request.');
    header("Location: expense_manager_dashboard.php");
    exit();
}

$claim_id = (int)($_POST['claim_id'] ?? 0);
$remarks  = trim($_POST['remarks'] ?? '');

/* Confirm this claim belongs to someone who reports to the current manager, and is pending */
$stmt = $conn->prepare("
    SELECT e.id FROM expenses e
    JOIN users u ON u.id = e.employee_id COLLATE utf8mb4_general_ci
    WHERE e.id = ? AND u.reporting_manager_id = ? AND e.status = 'pending'
");
$stmt->bind_param("ii", $claim_id, $manager_id);
$stmt->execute();
$found = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$found) {
    set_flash('warning', 'Claim not found or already processed.');
    header("Location: expense_manager_dashboard.php");
    exit();
}

$stmtM = $conn->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
$stmtM->bind_param("s", $manager_id);
$stmtM->execute();
$mgr = $stmtM->get_result()->fetch_assoc();
$stmtM->close();
$manager_name = trim(($mgr['first_name'] ?? '') . ' ' . ($mgr['last_name'] ?? '')) ?: ($_SESSION['username'] ?? 'Manager');

$stmt2 = $conn->prepare("UPDATE expenses SET status='approved', reviewed_by=?, reviewed_by_name=?, reviewed_at=NOW(), manager_remarks=?, updated_at=NOW() WHERE id=? AND status='pending'");
$remarks_val = $remarks !== '' ? $remarks : null;
$stmt2->bind_param("sssi", $manager_id, $manager_name, $remarks_val, $claim_id);
if ($stmt2->execute() && $stmt2->affected_rows > 0) {
    set_flash('success', "Claim #$claim_id approved.");
} else {
    set_flash('warning', 'Claim could not be approved (it may have already been processed).');
}
$stmt2->close();

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