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

redirect_if_not_authenticated();

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

$application_id = $_POST['application_id'] ?? null;
$action = $_POST['action'] ?? null;
$comments = $_POST['comments'] ?? '';

if (!$application_id || !$action) {
    header('Location: view_applications.php');
    exit();
}

$pdo = db();

// --- New Approval Workflow ---
$approval_levels = [
    1 => 'Sales Manager',
    2 => 'General Manager',
    3 => 'Managing Director'
];
// --- End New Approval Workflow ---

// Helper function to get user emails by role name
function get_user_emails_by_role($role_name, $pdo) {
    $stmt = $pdo->prepare('SELECT email FROM users u JOIN roles r ON u.role_id = r.id WHERE r.name = ?');
    $stmt->execute([$role_name]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

// Fetch application
$stmt = $pdo->prepare('SELECT * FROM customer_applications WHERE id = ?');
$stmt->execute([$application_id]);
$application = $stmt->fetch();

if (!$application) {
    die('Application not found.');
}

// Get applicant email
$stmt_applicant = $pdo->prepare('SELECT email FROM customer_contacts WHERE customer_application_id = ? AND is_primary = 1');
$stmt_applicant->execute([$application_id]);
$applicant_email = $stmt_applicant->fetchColumn();

// Get current user's role
$current_user_role_id = get_user_role_id();
$stmt_role = $pdo->prepare("SELECT name FROM roles WHERE id = ?");
$stmt_role->execute([$current_user_role_id]);
$current_user_role_name = $stmt_role->fetchColumn();

$current_level = $application['approval_level'];
$required_role = $approval_levels[$current_level] ?? null;

// Check if the current user has the required role for this level
if ($current_user_role_name !== $required_role && $current_user_role_name !== 'admin') {
    $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'You do not have permission to perform this action.'];
    header('Location: view_application.php?id=' . $application_id);
    exit();
}


try {
    $pdo->beginTransaction();

    // Log the action
    $stmt_log = $pdo->prepare("INSERT INTO application_approvals (application_id, approver_id, approval_level, status, comments) VALUES (?, ?, ?, ?, ?)");
    $stmt_log->execute([$application_id, get_user_id(), $current_level, ucfirst($action), $comments]);

    if ($action === 'approve') {
        $next_level = $current_level + 1;

        if (array_key_exists($next_level, $approval_levels)) {
            // Move to next approval level
            $next_role_name = $approval_levels[$next_level];
            $stmt_next_role = $pdo->prepare("SELECT id FROM roles WHERE name = ?");
            $stmt_next_role->execute([$next_role_name]);
            $next_role_id = $stmt_next_role->fetchColumn();

            $stmt_update = $pdo->prepare('UPDATE customer_applications SET approval_level = ?, current_approver_role_id = ?, status = \'Pending\' WHERE id = ?');
            $stmt_update->execute([$next_level, $next_role_id, $application_id]);

            $_SESSION['flash_message'] = ['type' => 'success', 'message' => "Application approved and sent to {$next_role_name}."];

            /*
            // Notify next approvers
            $next_approver_emails = get_user_emails_by_role($next_role_name, $pdo);
            if (!empty($next_approver_emails)) {
                $subject = "Application requires your approval: " . $application['company_name'];
                $body = "<p>A credit application for <b>{$application['company_name']}</b> requires your review.</p><p><a href='http://{\$_SERVER['HTTP_HOST']}/view_application.php?id={$application_id}'>View Application</a></p>";
                MailService::sendMail($next_approver_emails, $subject, $body);
            }
            */
        } else {
            // Final approval
            $stmt_update = $pdo->prepare("UPDATE customer_applications SET status = 'Approved', approval_level = NULL, current_approver_role_id = NULL WHERE id = ?");
            $stmt_update->execute([$application_id]);
            $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Application has been fully approved.'];
            
            /*
            // Notify applicant
            if ($applicant_email) {
                $subject = 'Your Application has been Approved: ' . $application['application_id'];
                $body = "<p>Congratulations! Your customer application ({$application['application_id']}) has been approved.</p>";
                MailService::sendMail($applicant_email, $subject, $body);
            }
            */
        }

    } elseif ($action === 'return') {
        $prev_level = $current_level - 1;

        if (array_key_exists($prev_level, $approval_levels)) {
             // Return to previous approval level
            $prev_role_name = $approval_levels[$prev_level];
            $stmt_prev_role = $pdo->prepare("SELECT id FROM roles WHERE name = ?");
            $stmt_prev_role->execute([$prev_role_name]);
            $prev_role_id = $stmt_prev_role->fetchColumn();

            $stmt_update = $pdo->prepare('UPDATE customer_applications SET approval_level = ?, current_approver_role_id = ?, status = \'Returned\' WHERE id = ?');
            $stmt_update->execute([$prev_level, $prev_role_id, $application_id]);

            $_SESSION['flash_message'] = ['type' => 'warning', 'message' => "Application returned to {$prev_role_name} for review."];

            /*
            // Notify previous approvers
            $prev_approver_emails = get_user_emails_by_role($prev_role_name, $pdo);
            if (!empty($prev_approver_emails)) {
                $subject = "Application returned for your review: " . $application['company_name'];
                $body = "<p>The application for <b>{$application['company_name']}</b> has been returned for your review with the following comments:</p><p><i>" . htmlspecialchars($comments) . "</i></p><p><a href='http://{\$_SERVER['HTTP_HOST']}/view_application.php?id={$application_id}'>View Application</a></p>";
                MailService::sendMail($prev_approver_emails, $subject, $body);
            }
            */
        } else {
            // Cannot return from the first level, this case should ideally be handled in the UI
             $_SESSION['flash_message'] = ['type' => 'danger', 'message' => "Cannot return the application from the first approval level."];
        }

    } elseif ($action === 'reject') {
        $stmt_update = $pdo->prepare("UPDATE customer_applications SET status = 'Rejected' WHERE id = ?");
        $stmt_update->execute([$application_id]);

        $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'Application has been rejected.'];

        /*
        // Notify applicant
        if ($applicant_email) {
            $subject = 'Your Application has been Rejected: ' . $application['application_id'];
            $body = "<p>We regret to inform you that your customer application ({$application['application_id']}) has been rejected. The following comments were provided:</p><p><i>" . htmlspecialchars($comments) . "</i></p>";
            MailService::sendMail($applicant_email, $subject, $body);
        }
        */
    }

    $pdo->commit();

} catch (Exception $e) {
    $pdo->rollBack();
    error_log('Approval processing failed: ' . $e->getMessage());
    $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'An error occurred while processing the application. Please try again.'];
}

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