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

redirect_if_not_authenticated();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['application_id'])) {
    header('Location: view_applications.php');
    exit();
}

$application_id = $_POST['application_id'];
$pdo = db();

// Get the role ID for the first approval level (Sales Manager)
$stmt_role = $pdo->prepare("SELECT id FROM roles WHERE name = 'Sales Manager'");
$stmt_role->execute();
$sales_manager_role_id = $stmt_role->fetchColumn();

if (!$sales_manager_role_id) {
    $_SESSION['flash_message'] = [
        'type' => 'danger',
        'message' => 'Error: Sales Manager role not found. Cannot submit for approval.'
    ];
    header('Location: view_application.php?id=' . $application_id);
    exit();
}

// Update the application to start the approval process
$stmt = $pdo->prepare(
    'UPDATE customer_applications 
     SET status = ?, approval_level = ?, current_approver_role_id = ? 
     WHERE id = ? AND status = ?'
);

$success = $stmt->execute([
    'Pending', 
    1, // Start at level 1
    $sales_manager_role_id, 
    $application_id, 
    'Draft' // Ensure we only update drafts
]);

if ($success && $stmt->rowCount() > 0) {
    // Create initial approval history entry
    $stmt_history = $pdo->prepare(
        'INSERT INTO application_approvals (application_id, approver_id, status, comments, created_at) VALUES (?, ?, ?, ?, NOW())'
    );
    $stmt_history->execute([
        $application_id,
        get_user_id(), // The user submitting the application
        'Submitted',
        'Application submitted for approval.'
    ]);

    $_SESSION['flash_message'] = [
        'type' => 'success',
        'message' => 'Application successfully submitted for approval.'
    ];
} else {
    $_SESSION['flash_message'] = [
        'type' => 'danger',
        'message' => 'Failed to submit application. It might not be in a draft state or another error occurred.'
    ];
}

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