<?php
session_start();

require_once 'includes/auth_helpers.php';
require_once 'db/config.php';

redirect_if_not_authenticated();

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: view_applications.php');
    exit();
}

$application_id = $_GET['id'];
$pdo = db();

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

// Fetch application details
$stmt = $pdo->prepare('SELECT a.*, r.name as current_approver_role FROM customer_applications a LEFT JOIN roles r ON a.current_approver_role_id = r.id WHERE a.id = ?');
$stmt->execute([$application_id]);
$application = $stmt->fetch();

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

// Fetch approval history
$stmt_history = $pdo->prepare('SELECT ah.*, u.username as approver_name FROM application_approvals ah JOIN users u ON ah.approver_id = u.id WHERE ah.application_id = ? ORDER BY ah.created_at DESC');
$stmt_history->execute([$application_id]);
$approval_history = $stmt_history->fetchAll();

// Fetch other details (contacts, addresses, etc.) - condensed for brevity
$contacts = $pdo->query("SELECT * FROM customer_contacts WHERE customer_application_id = {$application_id}")->fetchAll();
$addresses = $pdo->query("SELECT * FROM customer_addresses WHERE customer_application_id = {$application_id}")->fetchAll();
$trade_references = $pdo->query("SELECT * FROM customer_trade_references WHERE customer_application_id = {$application_id}")->fetchAll();
$bank_details = $pdo->query("SELECT * FROM customer_bank_details WHERE customer_application_id = {$application_id}")->fetch();
$principals = $pdo->query("SELECT * FROM customer_principals WHERE customer_application_id = {$application_id}")->fetchAll();

// Get current user 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;
$can_approve = ($current_user_role_name === $required_role || $current_user_role_name === 'admin');

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Application - <?= htmlspecialchars($application['application_id']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">Customer Master</a>
            <ul class="navbar-nav ms-auto">
                <li class="nav-item"><a class="nav-link" href="index.php">Dashboard</a></li>
                <li class="nav-item"><a class="nav-link" href="view_applications.php">View Applications</a></li>
                <li class="nav-item"><a class="nav-link" href="logout.php">Logout</a></li>
            </ul>
        </div>
    </nav>

    <div class="container mt-4">
        <?php if (isset($_SESSION['flash_message'])): ?>
            <div class="alert alert-<?= $_SESSION['flash_message']['type'] ?> alert-dismissible fade show" role="alert">
                <?= $_SESSION['flash_message']['message'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['flash_message']); ?>
        <?php endif; ?>

        <h2>Application Details: <?= htmlspecialchars($application['application_id']) ?></h2>

        <!-- Approval Status & History -->
        <div class="card mb-4">
            <div class="card-header">Approval Status & History</div>
            <div class="card-body">
                <h4>Current Status: 
                    <span class="badge bg-<?=
                        strtoupper($application['status']) === 'APPROVED' ? 'success' : (
                        strtoupper($application['status']) === 'REJECTED' ? 'danger' : (
                        strtoupper($application['status']) === 'RETURNED' ? 'warning' : 'secondary'
                        ))
                    ?>">
                        <?= htmlspecialchars(strtoupper($application['status'])) ?>
                    </span>
                </h4>
                <?php if ($application['status'] === 'Pending' && $application['current_approver_role']): ?>
                    <p class="text-muted">Waiting for approval from: <strong><?= htmlspecialchars($application['current_approver_role']) ?></strong></p>
                <?php endif; ?>

                <?php if ($application['status'] === 'Draft'): ?>
                    <form action="submit_for_approval.php" method="POST" class="mt-3">
                        <input type="hidden" name="application_id" value="<?= $application['id'] ?>">
                        <button type="submit" class="btn btn-primary">Submit for Approval</button>
                    </form>
                <?php endif; ?>

                <h5 class="mt-4">Approval History</h5>
                <?php if (empty($approval_history)): ?>
                    <p>No approval history found.</p>
                <?php else: ?>
                    <ul class="list-group">
                        <?php foreach ($approval_history as $history): ?>
                            <li class="list-group-item">
                                <p class="mb-1"><strong>Action:</strong> <?= htmlspecialchars($history['status']) ?></p>
                                <p class="mb-1"><strong>By:</strong> <?= htmlspecialchars($history['approver_name']) ?></p>
                                <?php if (!empty($history['comments'])): ?>
                                    <p class="mb-1"><strong>Comments:</strong> <?= nl2br(htmlspecialchars($history['comments'])) ?></p>
                                <?php endif; ?>
                                <small class="text-muted"><?= date('Y-m-d H:i:s', strtotime($history['created_at'])) ?></small>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>

        <!-- Approval Action Form -->
        <?php if ($can_approve && in_array($application['status'], ['Pending', 'Returned'])): ?>
        <div class="card mb-4">
            <div class="card-header">Approval Action</div>
            <div class="card-body">
                <form action="process_approval.php" method="POST">
                    <input type="hidden" name="application_id" value="<?= $application['id'] ?>">
                    <div class="mb-3">
                        <label for="comments" class="form-label">Comments (Required for Return/Reject)</label>
                        <textarea class="form-control" id="comments" name="comments" rows="3"></textarea>
                    </div>
                    <button type="submit" name="action" value="approve" class="btn btn-success">Approve</button>
                    <?php if ($current_level > 1): // Cannot return from the first level ?>
                        <button type="submit" name="action" value="return" class="btn btn-warning">Return</button>
                    <?php endif; ?>
                    <button type="submit" name="action" value="reject" class="btn btn-danger">Reject</button>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <!-- Tabs for Application Details -->
        <ul class="nav nav-tabs" id="myTab" role="tablist">
          <li class="nav-item" role="presentation">
            <button class="nav-link active" id="company-tab" data-bs-toggle="tab" data-bs-target="#company" type="button" role="tab" aria-controls="company" aria-selected="true">Company</button>
          </li>
           <li class="nav-item" role="presentation">
            <button class="nav-link" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summary" type="button" role="tab" aria-controls="summary" aria-selected="false">Summary</button>
          </li>
        </ul>
        
        <div class="tab-content" id="myTabContent">
          <div class="tab-pane fade show active" id="company" role="tabpanel" aria-labelledby="company-tab">
                <!-- Company Details -->
                <div class="card mb-4">
                    <div class="card-header">Company Details</div>
                    <div class="card-body">
                        <p><strong>Company Name:</strong> <?= htmlspecialchars($application['company_name']) ?></p>
                        <p><strong>Company Website:</strong> <a href="<?= htmlspecialchars($application['company_website']) ?>" target="_blank"><?= htmlspecialchars($application['company_website']) ?></a></p>
                        <p><strong>Company Phone:</strong> <?= htmlspecialchars($application['company_phone']) ?></p>
                    </div>
                </div>
          </div>
          <div class="tab-pane fade" id="summary" role="tabpanel" aria-labelledby="summary-tab">
                <!-- Application Summary -->
                <div class="card mb-4">
                    <div class="card-header">Application Summary</div>
                    <div class="card-body">
                        <p><strong>Test:</strong> Test</p>
                    </div>
                </div>
          </div>
        </div>

    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>