<?php
// api/leave.php
// Rockview University leave application workflow.
// Staff -> HOD -> Junior HR -> Registrar -> Senior HR (HQ) -> DVC1 (HQ).
// Official endorsements are QR-verifiable audit records.

declare(strict_types=1);

require_once __DIR__ . '/leave_common.php';

leave_ensure_tables($pdo);
$user = leave_current_user($pdo);
$profile = leave_official_profile($pdo, $user);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$input = in_array($method, ['POST','PUT','PATCH'], true) ? leave_input() : [];
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$action = strtolower(leave_clean($_GET['action'] ?? '', 40));
$scope = strtolower(leave_clean($_GET['scope'] ?? 'my', 40));

try {
    if ($method === 'GET' && $action === 'setup') {
        $year = (int)date('Y');
        $annual = leave_sync_annual_balance($pdo, (int)$user['id'], $year);

        $balanceStmt = $pdo->prepare('SELECT leave_type, leave_year, entitlement_days, carried_forward_days, used_days, adjustment_days, accrual_rate_month, last_accrual_month FROM leave_balances WHERE user_id = ? AND leave_year = ? ORDER BY leave_type');
        $balanceStmt->execute([(int)$user['id'], $year]);
        $balances = [];
        foreach ($balanceStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $available = (float)$row['entitlement_days'] + (float)$row['carried_forward_days'] + (float)$row['adjustment_days'] - (float)$row['used_days'];
            $row['available_days'] = $available;
            foreach (['entitlement_days','carried_forward_days','used_days','adjustment_days','accrual_rate_month','available_days'] as $key) {
                if (isset($row[$key])) $row[$key] = (float)$row[$key];
            }
            $balances[] = $row;
        }

        $routeReady = [];
        $routeErrors = [];
        $hod = leave_hod_for($pdo, $profile['department'], $profile['campus']);
        if ($hod) {
            $routeReady['hod'] = ['user_id'=>(int)$hod['user_id'], 'name'=>$hod['full_name'] ?? '', 'campus'=>$profile['campus']];
        } else {
            $routeErrors['hod'] = 'No HOD is assigned for this department at this campus.';
        }
        foreach (['junior_hr','registrar','senior_hr','dvc1'] as $stage) {
            $campusForStage = leave_routing_campus($pdo, $stage, $profile['campus']);
            $matches = leave_admin_candidates($pdo, $stage, $campusForStage);
            if (count($matches) === 1) {
                $routeReady[$stage] = ['user_id'=>(int)$matches[0]['user_id'], 'name'=>$matches[0]['full_name'] ?? $matches[0]['name'] ?? '', 'campus'=>$campusForStage];
            } elseif (count($matches) === 0) {
                $routeErrors[$stage] = 'No ' . leave_stage_label($stage) . ' is configured at ' . $campusForStage . '.';
            } else {
                $routeErrors[$stage] = 'More than one ' . leave_stage_label($stage) . ' is configured at ' . $campusForStage . '.';
            }
        }

        leave_json([
            'current_user' => $profile,
            'balances' => $balances,
            'annual_balance' => $annual,
            'monthly_accrual_days' => 2.0,
            'leave_types' => ['annual','compassionate','sick','maternity','paternity','study','unpaid','other'],
            'route_preview' => [
                ['stage'=>'hod','label'=>'HOD','scope'=>'Department + Campus'],
                ['stage'=>'junior_hr','label'=>'Junior HR','scope'=>'Campus'],
                ['stage'=>'registrar','label'=>'Registrar','scope'=>'Campus'],
                ['stage'=>'senior_hr','label'=>'Senior HR','scope'=>'Head Quarters'],
                ['stage'=>'dvc1','label'=>'DVC1','scope'=>'Head Quarters'],
            ],
            'route_ready' => $routeReady,
            'route_errors' => $routeErrors,
            'hr_access' => leave_hr_access($pdo, $user),
            'verification' => [
                'enabled' => true,
                'public_base_url' => leave_public_base_url(),
                'message' => 'Each submitted or processed leave action receives a unique QR verification record.',
            ],
        ]);
    }

    if ($method === 'GET' && $action === 'my_ledger') {
        $year = isset($_GET['year']) ? max(2000, min(2100, (int)$_GET['year'])) : (int)date('Y');
        $balance = leave_sync_annual_balance($pdo, (int)$user['id'], $year);

        $historySql = "SELECT
                id, leave_type, other_leave_type, start_date, end_date,
                expected_return_date, requested_days, available_days,
                previously_taken_days, closing_balance, status, current_stage,
                submitted_at, final_decision_at, updated_at,
                EXTRACT(YEAR FROM start_date)::INT AS leave_year
            FROM leave_applications
            WHERE applicant_user_id = ?";
        $historyParams = [(int)$user['id']];
        if (isset($_GET['year']) && (int)$_GET['year'] > 0) {
            $historySql .= " AND EXTRACT(YEAR FROM start_date) = ?";
            $historyParams[] = $year;
        }
        $historySql .= " ORDER BY start_date DESC, id DESC LIMIT 200";
        $historyStmt = $pdo->prepare($historySql);
        $historyStmt->execute($historyParams);
        $history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($history as &$leaveRow) {
            $leaveRow['id'] = (int)$leaveRow['id'];
            foreach (['requested_days','available_days','previously_taken_days','closing_balance'] as $key) {
                if (isset($leaveRow[$key]) && $leaveRow[$key] !== null) {
                    $leaveRow[$key] = (float)$leaveRow[$key];
                }
            }
        }
        unset($leaveRow);

        $adjustStmt = $pdo->prepare("SELECT
                id, leave_year, amount, before_balance, after_balance,
                reason, actor_name, actor_position, actor_campus, created_at
            FROM leave_balance_adjustments
            WHERE user_id = ? AND leave_year = ?
            ORDER BY created_at DESC, id DESC
            LIMIT 100");
        $adjustStmt->execute([(int)$user['id'], $year]);
        $adjustments = $adjustStmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($adjustments as &$adjustRow) {
            $adjustRow['id'] = (int)$adjustRow['id'];
            foreach (['amount','before_balance','after_balance'] as $key) {
                $adjustRow[$key] = (float)($adjustRow[$key] ?? 0);
            }
        }
        unset($adjustRow);

        $approved = 0;
        $pending = 0;
        $daysTaken = 0.0;
        foreach ($history as $leaveRow) {
            $status = strtolower((string)($leaveRow['status'] ?? ''));
            if ($status === 'approved') {
                $approved++;
                $daysTaken += (float)($leaveRow['requested_days'] ?? 0);
            } elseif (in_array($status, ['pending','returned'], true)) {
                $pending++;
            }
        }

        leave_json([
            'current_user' => $profile,
            'year' => $year,
            'balance' => $balance,
            'summary' => [
                'approved_leave_records' => $approved,
                'pending_leave_records' => $pending,
                'days_taken_history' => $daysTaken,
                'days_taken_this_year' => $daysTaken,
                'monthly_accrual_days' => 2.0,
            ],
            'leave_history' => $history,
            'adjustments' => $adjustments,
        ]);
    }

    if ($method === 'GET' && $id > 0) {
        $row = leave_full_row($pdo, $id, $user);
        if (!$row) leave_json(['detail' => 'Leave application not found.'], 404);
        $canSee = $row['is_owner'] || $row['action_required'];
        if (!$canSee) {
            $check = $pdo->prepare('SELECT 1 FROM leave_routes WHERE leave_id = ? AND actor_user_id = ? LIMIT 1');
            $check->execute([$id, (int)$user['id']]);
            $canSee = (bool)$check->fetchColumn();
        }
        // Junior/Senior HR may reopen employee leave records within their
        // authorized HR ledger scope even when they are not the current route.
        if (!$canSee) {
            $access = leave_hr_access($pdo, $user);
            if ($access['enabled']) {
                $sameCampus = leave_campus_key((string)$row['campus']) === leave_campus_key((string)$access['campus']);
                if ($access['scope'] === 'all_campuses' || $sameCampus) $canSee = true;
            }
        }
        if (!$canSee) leave_json(['detail' => 'You are not authorized to view this leave application.'], 403);
        leave_json(['data' => $row]);
    }

    if ($method === 'GET') {
        $params = [];
        $where = '';
        if ($scope === 'action') {
            $where = "WHERE current_recipient_user_id = ? AND status = 'pending'";
            $params[] = (int)$user['id'];
        } elseif ($scope === 'completed') {
            $where = "WHERE (applicant_user_id = ? OR EXISTS (SELECT 1 FROM leave_routes lr WHERE lr.leave_id = leave_applications.id AND lr.actor_user_id = ?)) AND status IN ('approved','rejected','withdrawn')";
            $params[] = (int)$user['id'];
            $params[] = (int)$user['id'];
        } elseif ($scope === 'all_visible') {
            $where = 'WHERE applicant_user_id = ? OR current_recipient_user_id = ? OR EXISTS (SELECT 1 FROM leave_routes lr WHERE lr.leave_id = leave_applications.id AND lr.actor_user_id = ?)';
            $params[] = (int)$user['id'];
            $params[] = (int)$user['id'];
            $params[] = (int)$user['id'];
        } else {
            $where = 'WHERE applicant_user_id = ?';
            $params[] = (int)$user['id'];
        }
        $stmt = $pdo->prepare("SELECT * FROM leave_applications $where ORDER BY updated_at DESC, id DESC");
        $stmt->execute($params);
        $rows = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) $rows[] = leave_public_row($pdo, $row, $user);

        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM leave_applications WHERE current_recipient_user_id = ? AND status = 'pending'");
        $countStmt->execute([(int)$user['id']]);
        $actionCount = (int)$countStmt->fetchColumn();
        leave_json(['data' => $rows, 'count' => count($rows), 'action_required_count' => $actionCount, 'current_user' => $profile]);
    }

    if ($method === 'POST' && $id <= 0 && $action === '') {
        $department = $profile['department'];
        $campus = $profile['campus'];
        if ($department === '') leave_json(['detail' => 'Your staff profile has no department. Assign the department before submitting leave.'], 422);
        if ($campus === '') leave_json(['detail' => 'Your staff profile has no campus. Assign the campus before submitting leave.'], 422);

        $personnelNo = leave_clean($input['personnel_no'] ?? '', 120);
        $positionTitle = leave_clean($input['position_title'] ?? $profile['position'], 180);
        if ($positionTitle === '') leave_json(['detail' => 'Position / job title is required.'], 422);
        $leaveType = strtolower(leave_clean($input['leave_type'] ?? '', 60));
        $allowedTypes = ['annual','compassionate','sick','maternity','paternity','study','unpaid','other'];
        if (!in_array($leaveType, $allowedTypes, true)) leave_json(['detail' => 'Select a valid leave type.'], 422);
        $otherType = leave_clean($input['other_leave_type'] ?? '', 180);
        if ($leaveType === 'other' && $otherType === '') leave_json(['detail' => 'Specify the other leave type.'], 422);
        $reason = leave_clean($input['reason'] ?? '', 5000);
        if ($reason === '') leave_json(['detail' => 'Reason for taking leave is required.'], 422);

        $start = leave_clean($input['start_date'] ?? '', 20);
        $end = leave_clean($input['end_date'] ?? '', 20);
        $returnDate = leave_clean($input['expected_return_date'] ?? '', 20);
        $days = leave_requested_days($start, $end);
        if ($days <= 0) leave_json(['detail' => 'Start date and end date are invalid. End date must not be before start date.'], 422);
        if ($returnDate === '') leave_json(['detail' => 'Expected return-to-duty date is required.'], 422);

        if ($leaveType === 'annual') {
            $balance = leave_sync_annual_balance($pdo, (int)$user['id'], (int)substr($start, 0, 4));
            if ($days > (float)$balance['available_days']) {
                leave_json(['detail' => 'You are applying for ' . $days . ' annual leave day(s), but your current available balance is ' . number_format((float)$balance['available_days'], 2) . ' day(s). Contact HR if the balance needs correction.'], 422);
            }
        }

        $address = leave_clean($input['address_while_on_leave'] ?? '', 3000);
        $contactName = leave_clean($input['emergency_contact_name'] ?? '', 255);
        $contactPhone = leave_clean($input['emergency_contact_phone'] ?? '', 120);
        $contactRelationship = leave_clean($input['emergency_contact_relationship'] ?? '', 120);
        $contactAddress = leave_clean($input['emergency_contact_address'] ?? '', 3000);

        $hod = leave_resolve_recipient($pdo, 'hod', $campus, $department);
        $legacyMark = leave_signature_mark($profile['name']);
        $appQr = leave_new_qr_token();

        $pdo->beginTransaction();
        $stmt = $pdo->prepare("INSERT INTO leave_applications (
            applicant_user_id, applicant_name, applicant_email, applicant_phone, personnel_no,
            position_title, department, campus, leave_type, other_leave_type, reason,
            start_date, end_date, expected_return_date, requested_days,
            address_while_on_leave, emergency_contact_name, emergency_contact_phone,
            emergency_contact_relationship, emergency_contact_address,
            current_stage, current_recipient_user_id, current_recipient_label, current_recipient_campus,
            status, applicant_signature_mark, applicant_qr_token
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'hod', ?, ?, ?, 'pending', ?, ?) RETURNING id");
        $stmt->execute([
            (int)$user['id'], $profile['name'], $profile['email'], $profile['phone'], $personnelNo,
            $positionTitle, $department, $campus, $leaveType, $otherType !== '' ? $otherType : null, $reason,
            $start, $end, $returnDate, $days,
            $address !== '' ? $address : null, $contactName !== '' ? $contactName : null, $contactPhone !== '' ? $contactPhone : null,
            $contactRelationship !== '' ? $contactRelationship : null, $contactAddress !== '' ? $contactAddress : null,
            $hod['user_id'], $hod['label'], $hod['campus'], $legacyMark, $appQr,
        ]);
        $leaveId = (int)$stmt->fetchColumn();
        leave_route_event($pdo, [
            'leave_id'=>$leaveId, 'action'=>'submitted', 'from_stage'=>'staff', 'to_stage'=>'hod',
            'actor_user_id'=>(int)$user['id'], 'actor_name'=>$profile['name'], 'actor_position'=>$positionTitle,
            'actor_campus'=>$campus, 'to_user_id'=>$hod['user_id'], 'to_label'=>$hod['label'], 'to_campus'=>$hod['campus'],
            'decision'=>'submitted', 'remarks'=>'Leave application submitted to the department HOD.', 'signature_mark'=>$legacyMark,
        ]);
        leave_notify($pdo, $leaveId, (int)$hod['user_id'], 'action_required', 'Leave application requires HOD action', $profile['name'] . ' submitted a ' . strtoupper($leaveType) . ' leave application for ' . $days . ' day(s).');
        leave_notify($pdo, $leaveId, (int)$user['id'], 'submitted', 'Leave application submitted', 'Your leave application #' . $leaveId . ' was submitted to your HOD. The form now carries a QR-verifiable submission record.');
        $pdo->commit();
        leave_json([
            'message'=>'Leave application submitted successfully.',
            'id'=>$leaveId,
            'verification_url'=>leave_verification_url($appQr),
        ], 201);
    }

    if ($method === 'POST' && $id > 0 && $action !== '') {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare('SELECT * FROM leave_applications WHERE id = ? FOR UPDATE');
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            $pdo->rollBack();
            leave_json(['detail'=>'Leave application not found.'],404);
        }

        $isOwner = (int)$row['applicant_user_id'] === (int)$user['id'];
        $isRecipient = (int)($row['current_recipient_user_id'] ?? 0) === (int)$user['id'];
        $remarks = leave_clean($input['remarks'] ?? '', 5000);
        $legacyMark = leave_signature_mark($profile['name']);

        if ($action === 'withdraw') {
            if (!$isOwner || $row['status'] !== 'pending') {
                $pdo->rollBack();
                leave_json(['detail'=>'Only the applicant may withdraw a pending leave application.'],403);
            }
            $pdo->prepare("UPDATE leave_applications SET status='withdrawn', current_recipient_user_id=NULL, current_recipient_label=NULL, current_recipient_campus=NULL, final_decision_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id=?")->execute([$id]);
            $event = leave_route_event($pdo,[
                'leave_id'=>$id,'action'=>'withdrawn','from_stage'=>$row['current_stage'],'to_stage'=>null,
                'actor_user_id'=>(int)$user['id'],'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],
                'decision'=>'withdrawn','remarks'=>$remarks,'signature_mark'=>$legacyMark,
            ]);
            leave_notify($pdo,$id,(int)$user['id'],'final','Leave application withdrawn','You withdrew leave application #'.$id.'.');
            $pdo->commit();
            leave_json(['message'=>'Leave application withdrawn.','verification_url'=>$event['verification_url']]);
        }

        if ($action === 'resubmit') {
            if (!$isOwner || $row['status'] !== 'returned') {
                $pdo->rollBack();
                leave_json(['detail'=>'Only the applicant may resubmit a returned leave application.'],403);
            }
            $hod = leave_resolve_recipient($pdo,'hod',$row['campus'],$row['department']);
            $pdo->prepare("UPDATE leave_applications SET status='pending', current_stage='hod', current_recipient_user_id=?, current_recipient_label=?, current_recipient_campus=?, updated_at=CURRENT_TIMESTAMP WHERE id=?")
                ->execute([$hod['user_id'],$hod['label'],$hod['campus'],$id]);
            $event = leave_route_event($pdo,[
                'leave_id'=>$id,'action'=>'resubmitted','from_stage'=>'staff','to_stage'=>'hod',
                'actor_user_id'=>(int)$user['id'],'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],
                'to_user_id'=>$hod['user_id'],'to_label'=>$hod['label'],'to_campus'=>$hod['campus'],
                'decision'=>'resubmitted','remarks'=>$remarks,'signature_mark'=>$legacyMark,
            ]);
            leave_notify($pdo,$id,(int)$hod['user_id'],'action_required','Returned leave application resubmitted',$row['applicant_name'].' resubmitted leave application #'.$id.'.');
            leave_notify($pdo,$id,(int)$user['id'],'progress','Leave application resubmitted','Your leave application was resubmitted to your HOD.');
            $pdo->commit();
            leave_json(['message'=>'Leave application resubmitted to HOD.','verification_url'=>$event['verification_url']]);
        }

        if (!$isRecipient || $row['status'] !== 'pending') {
            $pdo->rollBack();
            leave_json(['detail'=>'This leave application is not currently assigned to you for action.'],403);
        }

        $stage = (string)$row['current_stage'];
        $allowed = leave_stage_actions($stage);
        if (!in_array($action,$allowed,true)) {
            $pdo->rollBack();
            leave_json(['detail'=>'Action '.$action.' is not allowed at '.leave_stage_label($stage).'.'],422);
        }
        if (in_array($action,['return','reject'],true) && $remarks === '') {
            $pdo->rollBack();
            leave_json(['detail'=>'Remarks are required when returning or rejecting a leave application.'],422);
        }

        // Junior HR no longer types balances manually. The authoritative annual
        // leave ledger is synchronized automatically at +2 days per month.
        if ($stage === 'junior_hr' && $action === 'verify') {
            if ((string)$row['leave_type'] === 'annual') {
                $leaveYear = (int)substr((string)$row['start_date'], 0, 4);
                $balance = leave_sync_annual_balance($pdo, (int)$row['applicant_user_id'], $leaveYear);
                $available = (float)$balance['available_days'];
                $previous = (float)$balance['used_days'];
                $accrual = (float)$balance['accrual_rate_month'];
                $closing = $available - (float)$row['requested_days'];
                if ($closing < 0) {
                    $pdo->rollBack();
                    leave_json(['detail'=>'This employee has only '.number_format($available,2).' annual leave day(s) available but applied for '.number_format((float)$row['requested_days'],2).'. Adjust the HR ledger first or return the application.'],422);
                }
                $pdo->prepare('UPDATE leave_applications SET available_days=?, previously_taken_days=?, accrual_rate_month=?, closing_balance=?, balance_confirmed_by_user_id=?, balance_confirmed_at=CURRENT_TIMESTAMP WHERE id=?')
                    ->execute([$available,$previous,$accrual,$closing,(int)$user['id'],$id]);
            } else {
                $pdo->prepare('UPDATE leave_applications SET balance_confirmed_by_user_id=?, balance_confirmed_at=CURRENT_TIMESTAMP WHERE id=?')
                    ->execute([(int)$user['id'],$id]);
            }
        }

        if ($action === 'return') {
            $returnStage = leave_return_stage($stage);
            if ($returnStage === null) {
                $pdo->prepare("UPDATE leave_applications SET status='returned', current_recipient_user_id=NULL, current_recipient_label='Applicant', current_recipient_campus=campus, updated_at=CURRENT_TIMESTAMP WHERE id=?")->execute([$id]);
                $event = leave_route_event($pdo,[
                    'leave_id'=>$id,'action'=>'returned','from_stage'=>$stage,'to_stage'=>'staff','actor_user_id'=>(int)$user['id'],
                    'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],
                    'to_user_id'=>$row['applicant_user_id'],'to_label'=>'Applicant','to_campus'=>$row['campus'],'decision'=>'returned','remarks'=>$remarks,'signature_mark'=>$legacyMark,
                ]);
                leave_notify($pdo,$id,(int)$row['applicant_user_id'],'returned','Leave application returned for correction',leave_stage_label($stage).' returned your leave application. Remarks: '.$remarks);
                $pdo->commit();
                leave_json(['message'=>'Leave application returned to the applicant.','verification_url'=>$event['verification_url']]);
            }

            $returnRecipient = leave_resolve_recipient($pdo,$returnStage,$row['campus'],$row['department']);
            $pdo->prepare("UPDATE leave_applications SET status='pending', current_stage=?, current_recipient_user_id=?, current_recipient_label=?, current_recipient_campus=?, updated_at=CURRENT_TIMESTAMP WHERE id=?")
                ->execute([$returnStage,$returnRecipient['user_id'],$returnRecipient['label'],$returnRecipient['campus'],$id]);
            $event = leave_route_event($pdo,[
                'leave_id'=>$id,'action'=>'returned','from_stage'=>$stage,'to_stage'=>$returnStage,'actor_user_id'=>(int)$user['id'],
                'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],
                'to_user_id'=>$returnRecipient['user_id'],'to_label'=>$returnRecipient['label'],'to_campus'=>$returnRecipient['campus'],'decision'=>'returned','remarks'=>$remarks,'signature_mark'=>$legacyMark,
            ]);
            leave_notify($pdo,$id,(int)$returnRecipient['user_id'],'action_required','Leave application returned for correction',leave_stage_label($stage).' returned leave application #'.$id.'. Remarks: '.$remarks);
            leave_notify($pdo,$id,(int)$row['applicant_user_id'],'progress','Leave application returned within the approval chain',leave_stage_label($stage).' returned your leave application to '.leave_stage_label($returnStage).' for correction.');
            $pdo->commit();
            leave_json(['message'=>'Leave application returned to '.leave_stage_label($returnStage).'.','verification_url'=>$event['verification_url']]);
        }

        if ($action === 'reject') {
            $pdo->prepare("UPDATE leave_applications SET status='rejected', current_recipient_user_id=NULL, current_recipient_label=NULL, current_recipient_campus=NULL, final_decision_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id=?")->execute([$id]);
            $event = leave_route_event($pdo,[
                'leave_id'=>$id,'action'=>'rejected','from_stage'=>$stage,'to_stage'=>null,'actor_user_id'=>(int)$user['id'],
                'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],'decision'=>'rejected','remarks'=>$remarks,'signature_mark'=>$legacyMark,
            ]);
            leave_notify($pdo,$id,(int)$row['applicant_user_id'],'final','Leave application not approved',leave_stage_label($stage).' did not approve your leave application. Remarks: '.$remarks);
            $pdo->commit();
            leave_json(['message'=>'Leave application rejected.','verification_url'=>$event['verification_url']]);
        }

        if ($stage === 'dvc1' && $action === 'approve') {
            if ((string)$row['leave_type'] === 'annual') {
                $leaveYear = (int)substr((string)$row['start_date'], 0, 4);
                $balance = leave_sync_annual_balance($pdo, (int)$row['applicant_user_id'], $leaveYear);
                if ((float)$row['requested_days'] > (float)$balance['available_days']) {
                    $pdo->rollBack();
                    leave_json(['detail'=>'The employee no longer has sufficient annual leave balance for final approval. HR must review the ledger.'],422);
                }
                $balanceUpdate = $pdo->prepare("UPDATE leave_balances
                    SET used_days = used_days + ?, updated_by_user_id = ?, updated_at = CURRENT_TIMESTAMP
                    WHERE user_id = ? AND leave_type = 'annual' AND leave_year = ?");
                $balanceUpdate->execute([
                    (float)$row['requested_days'],
                    (int)$user['id'],
                    (int)$row['applicant_user_id'],
                    $leaveYear,
                ]);
            }

            $pdo->prepare("UPDATE leave_applications SET status='approved', current_recipient_user_id=NULL, current_recipient_label=NULL, current_recipient_campus=NULL, final_decision_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE id=?")->execute([$id]);
            $event = leave_route_event($pdo,[
                'leave_id'=>$id,'action'=>'approved','from_stage'=>'dvc1','to_stage'=>null,'actor_user_id'=>(int)$user['id'],
                'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],'decision'=>'approved','remarks'=>$remarks,'signature_mark'=>$legacyMark,
            ]);
            leave_notify($pdo,$id,(int)$row['applicant_user_id'],'final','Leave application approved','Your leave application has received final approval from DVC1. The approval can be verified using the QR record on the leave form.');
            $pdo->commit();
            leave_json(['message'=>'Leave application approved by DVC1.','verification_url'=>$event['verification_url']]);
        }

        // Registrar is not a terminal gate. Positive routing always continues:
        // HOD -> Junior HR -> Registrar -> Senior HR HQ -> DVC1 HQ.
        $expectedPositive = match ($stage) {
            'hod' => 'recommend',
            'junior_hr' => 'verify',
            'registrar' => 'recommend',
            'senior_hr' => 'recommend',
            default => '',
        };
        if ($action !== $expectedPositive) {
            $pdo->rollBack();
            leave_json(['detail'=>'Unsupported positive action for this stage.'],422);
        }
        $nextStage = leave_next_stage($stage);
        if ($nextStage === null) {
            $pdo->rollBack();
            leave_json(['detail'=>'No next stage is configured.'],422);
        }
        $recipient = leave_resolve_recipient($pdo,$nextStage,$row['campus'],$row['department']);
        $pdo->prepare("UPDATE leave_applications SET current_stage=?, current_recipient_user_id=?, current_recipient_label=?, current_recipient_campus=?, updated_at=CURRENT_TIMESTAMP WHERE id=?")
            ->execute([$nextStage,$recipient['user_id'],$recipient['label'],$recipient['campus'],$id]);
        $event = leave_route_event($pdo,[
            'leave_id'=>$id,'action'=>'routed','from_stage'=>$stage,'to_stage'=>$nextStage,'actor_user_id'=>(int)$user['id'],
            'actor_name'=>$profile['name'],'actor_position'=>$profile['position'],'actor_campus'=>$profile['campus'],
            'to_user_id'=>$recipient['user_id'],'to_label'=>$recipient['label'],'to_campus'=>$recipient['campus'],'decision'=>$action,'remarks'=>$remarks,'signature_mark'=>$legacyMark,
        ]);
        leave_notify($pdo,$id,(int)$recipient['user_id'],'action_required','Leave application requires your action',$row['applicant_name'].' leave application is now at '.leave_stage_label($nextStage).'.');
        leave_notify($pdo,$id,(int)$row['applicant_user_id'],'progress','Leave application routed',leave_stage_label($stage).' routed your leave application to '.leave_stage_label($nextStage).'.');
        $pdo->commit();
        leave_json(['message'=>'Leave application routed to '.leave_stage_label($nextStage).'.','next_stage'=>$nextStage,'verification_url'=>$event['verification_url']]);
    }

    leave_json(['detail'=>'Unsupported leave workflow operation.'],405);
} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    leave_json(['detail'=>'Database error: '.$e->getMessage()],500);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    leave_json(['detail'=>'Leave workflow error: '.$e->getMessage()],500);
}
