<?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;

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

$pdo = db();

// Helper function to get user emails by role name
function get_user_emails_by_role($role_name, $pdo) {
    $stmt = $pdo->prepare('SELECT u.email FROM users u JOIN user_roles ur ON u.id = ur.user_id JOIN roles r ON ur.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.');
}

// Check permission
$approval_level = $application['approval_level'];
$permission_needed = 'approve_level_' . $approval_level;
if (!hasPermission($permission_needed)) {
    $_SESSION['flash_message'] = [
        'type' => 'danger',
        'message' => 'You do not have permission to perform this action.'
    ];
    header('Location: view_application.php?id=' . $application_id);
    exit();
}

// 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();

try {
    if ($action === 'approve') {
        $next_approval_level = $approval_level + 1;
        $next_approver_role_name = 'Approver Level ' . $next_approval_level;
        
        $stmt_role = $pdo->prepare("SELECT id FROM roles WHERE name = ?");
        $stmt_role->execute([$next_approver_role_name]);
        $next_approver_role = $stmt_role->fetch();

        if ($next_approver_role) {
            // Move to next approval level
            $stmt = $pdo->prepare('UPDATE customer_applications SET approval_level = ?, current_approver_role_id = ? WHERE id = ?');
            $stmt->execute([$next_approval_level, $next_approver_role['id'], $application_id]);
            $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Application approved and moved to the next level.'];

            // Notify next approvers
            $next_approver_emails = get_user_emails_by_role($next_approver_role_name, $pdo);
            if (!empty($next_approver_emails)) {
                // Get Sales Rep name
                $stmt_sales_rep = $pdo->prepare('SELECT name FROM users WHERE id = ?');
                $stmt_sales_rep->execute([$application['created_by_user_id']]);
                $sales_rep_name = $stmt_sales_rep->fetchColumn();

                // Get Credit Amount
                $stmt_credit = $pdo->prepare('SELECT requested_credit_limit FROM financial_credit_details WHERE customer_application_id = ?');
                $stmt_credit->execute([$application_id]);
                $credit_amount = $stmt_credit->fetchColumn();

                $subject = 'Credit Application - ' . $application['company_name'];
                $submission_date = date('Y-m-d');
                $body = "
                    <p>A new credit application requires your approval.</p>
                    <p><strong>Customer Name:</strong> {$application['company_name']}</p>
                    <p><strong>Sales Rep:</strong> {$sales_rep_name}</p>
                    <p><strong>Credit Amount:</strong> $" . number_format($credit_amount, 2) . "</p>
                    <p><strong>Submission Date:</strong> {$submission_date}</p>
                    <p><a href='http://{$_SERVER['HTTP_HOST']}/view_application.php?id={$application_id}' style='display: inline-block; padding: 10px 20px; background-color: #007bff; color: #fff; text-decoration: none;'>View Application</a></p>
                ";
                MailService::sendMail($next_approver_emails, $subject, $body);
            }
        } else {
            // Final approval
            $stmt = $pdo->prepare("UPDATE customer_applications SET status = 'APPROVED', approval_level = NULL, current_approver_role_id = NULL WHERE id = ?");
            $stmt->execute([$application_id]);
            $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Application 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 === 'reject') {
        $stmt = $pdo->prepare("UPDATE customer_applications SET status = 'REJECTED' WHERE id = ?");
        $stmt->execute([$application_id]);
        $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Application 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.</p>";
            MailService::sendMail($applicant_email, $subject, $body);
        }
    }

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

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