<?php
session_start();
require_once 'includes/auth_helpers.php';
require_once 'db/config.php';

redirect_if_not_authenticated();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

$application_id = $_POST['application_id'] ?? null;
$new_status = $_POST['status'] ?? null;
$comments = $_POST['comments'] ?? '';

if (!$application_id || !in_array($new_status, ['approved', 'rejected', 'reverted'])) {
    $_SESSION['message'] = 'Invalid request.';
    $_SESSION['message_type'] = 'danger';
    header('Location: index.php');
    exit();
}

$pdo = db();

try {
    // Get current application details
    $stmt_app = $pdo->prepare("SELECT approval_level, current_approver_role_id FROM customer_applications WHERE id = ?");
    $stmt_app->execute([$application_id]);
    $application = $stmt_app->fetch(PDO::FETCH_ASSOC);

    if (!$application) {
        $_SESSION['message'] = 'Application not found.';
        $_SESSION['message_type'] = 'danger';
        header('Location: index.php');
        exit();
    }

    $current_level = $application['approval_level'];
    $current_approver_role_id = $application['current_approver_role_id'];
    $user_role_id = $_SESSION['user']['role_id'];

    // Check if the user has permission to approve at this level
    if ($user_role_id != $current_approver_role_id) {
        $_SESSION['message'] = 'You do not have permission to approve this application at the current level.';
        $_SESSION['message_type'] = 'danger';
        header('Location: view_application.php?id=' . $application_id);
        exit();
    }

    $pdo->beginTransaction();

    // Insert into application_approvals
    $stmt_approval = $pdo->prepare(
        'INSERT INTO application_approvals (application_id, approver_id, approval_level, status, comments) VALUES (?, ?, ?, ?, ?)'
    );
    $stmt_approval->execute([$application_id, $_SESSION['user']['id'], $current_level, $new_status, $comments]);

    if ($new_status === 'approved') {
        $next_level = $current_level + 1;
        if ($next_level <= 7) {
            // Get the role ID for the next approval level
            $stmt_role = $pdo->prepare("SELECT id FROM roles WHERE name = ?");
            $stmt_role->execute(['Approver Level ' . $next_level]);
            $next_approver_role = $stmt_role->fetch(PDO::FETCH_ASSOC);
            $next_approver_role_id = $next_approver_role ? $next_approver_role['id'] : null;

            $stmt_update = $pdo->prepare(
                'UPDATE customer_applications SET approval_level = ?, current_approver_role_id = ? WHERE id = ?'
            );
            $stmt_update->execute([$next_level, $next_approver_role_id, $application_id]);
            $_SESSION['message'] = "Application approved and moved to the next level.";

        } else {
            $stmt_update = $pdo->prepare(
                "UPDATE customer_applications SET status = 'APPROVED', approval_level = 7, current_approver_role_id = NULL WHERE id = ?"
            );
            $stmt_update->execute([$application_id]);
            $_SESSION['message'] = "Application approved.";
        }
    } elseif ($new_status === 'reverted') { // Reverted
        $stmt_update = $pdo->prepare(
            "UPDATE customer_applications SET status = 'REVERTED' WHERE id = ?"
        );
        $stmt_update->execute([$application_id]);
        $_SESSION['message'] = "Application reverted to the applicant for amendments.";
    } else { // Rejected
        $stmt_update = $pdo->prepare(
            "UPDATE customer_applications SET status = 'REJECTED', current_approver_role_id = NULL WHERE id = ?"
        );
        $stmt_update->execute([$application_id]);
        $_SESSION['message'] = "Application rejected.";
    }

    $pdo->commit();
    $_SESSION['message_type'] = 'success';

} catch (PDOException $e) {
    $pdo->rollBack();
    $_SESSION['message'] = 'Database error: ' . $e->getMessage();
    $_SESSION['message_type'] = 'danger';
}

header('Location: view_application.php?id=' . $application_id);
exit();
