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

// Protect route: check if user is logged in
if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit();
}

$user = $_SESSION['user'];

// Dynamic project data from environment
$projectName = $_SERVER['PROJECT_NAME'] ?? 'Customer Master';
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Customer Master Registration & Maintenance';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Dashboard - <?php echo htmlspecialchars($projectName); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($projectDescription); ?>">
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:title" content="<?php echo htmlspecialchars($projectName); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($projectDescription); ?>">
    <?php if ($projectImageUrl): ?>
    <meta property="og:image" content="<?php echo htmlspecialchars($projectImageUrl); ?>">
    <?php endif; ?>

    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:title" content="<?php echo htmlspecialchars($projectName); ?>">
    <meta property="twitter:description" content="<?php echo htmlspecialchars($projectDescription); ?>">
    <?php if ($projectImageUrl): ?>
    <meta property="twitter:image" content="<?php echo htmlspecialchars($projectImageUrl); ?>">
    <?php endif; ?>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#"><i class="bi bi-person-vcard"></i> <?php echo htmlspecialchars($projectName); ?></a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="mainNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">Dashboard</a>
                    </li>
                    <?php if (hasPermission('manage_users')): ?>
                    <li class="nav-item">
                        <a class="nav-link" href="manage_users.php">Manage Users</a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a class="nav-link" href="view_applications.php">View Applications</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                     <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> <?php echo htmlspecialchars($user['username']); ?>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="profile.php">Profile</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="bi bi-box-arrow-right"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <main class="container mt-4">
        <?php if (isset($_SESSION['flash_message'])): ?>
            <div class="alert alert-<?php echo $_SESSION['flash_message']['type']; ?> alert-dismissible fade show" role="alert">
                <?php echo $_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; ?>
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3">Dashboard</h1>
            <?php if (hasPermission('create_application')): ?>
            <a href="new_application.php" class="btn btn-primary"><i class="bi bi-plus-circle"></i> New Customer Application</a>
            <?php endif; ?>
        </div>

        <p>Your dashboard is ready. From here you can manage customer applications.</p>

        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="bi bi-card-list"></i> Submitted Applications</h5>
            </div>
                            <div class="card-body">
                                <form action="index.php" method="GET" class="row g-3 align-items-center mb-3">
                                    <div class="col-auto">
                                        <label for="statusFilter" class="col-form-label">Filter by Status:</label>
                                    </div>
                                    <div class="col-auto">
                                        <select name="status" id="statusFilter" class="form-select">
                                            <option value="">All</option>
                                            <option value="draft" <?php echo (($_GET['status'] ?? '') === 'draft' ? 'selected' : ''); ?>>Draft</option>
                                            <option value="pending_approval" <?php echo (($_GET['status'] ?? '') === 'pending_approval' ? 'selected' : ''); ?>>Pending Approval</option>
                                            <option value="approved" <?php echo (($_GET['status'] ?? '') === 'approved' ? 'selected' : ''); ?>>Approved</option>
                                            <option value="rejected" <?php echo (($_GET['status'] ?? '') === 'rejected' ? 'selected' : ''); ?>>Rejected</option>
                                            <option value="reverted" <?php echo (($_GET['status'] ?? '') === 'reverted' ? 'selected' : ''); ?>>Reverted</option>
                                        </select>
                                    </div>
                                    <div class="col-auto">
                                        <button type="submit" class="btn btn-info">Filter</button>
                                    </div>
                                </form>
                            <?php
                            require_once 'db/config.php';
            
                            try {
                                $pdo = db();
            
                                function getSortIcon($column, $sort_column, $sort_order) {
                                    if ($column === $sort_column) {
                                        return $sort_order === 'ASC' ? ' <i class="bi bi-arrow-up"></i>' : ' <i class="bi bi-arrow-down"></i>';
                                    }
                                    return '';
                                }

                                function getStatusBadgeClass($status) {
                                    switch ($status) {
                                        case 'pending_approval':
                                            return 'bg-warning';
                                        case 'approved':
                                            return 'bg-success';
                                        case 'rejected':
                                            return 'bg-danger';
                                        case 'reverted':
                                            return 'bg-info';
                                        case 'draft':
                                        default:
                                            return 'bg-secondary';
                                    }
                                }
            
                                $sort_column = $_GET['sort'] ?? 'created_at';
                                $sort_order = $_GET['order'] ?? 'DESC';
                                $valid_columns = ['id', 'application_id', 'company_name', 'status', 'created_at'];
                                if (!in_array($sort_column, $valid_columns)) {
                                    $sort_column = 'created_at';
                                }
            
                                $status_filter = $_GET['status'] ?? '';
                                $sql = "SELECT id, application_id, company_name, status, created_at FROM customer_applications";
                                $params = [];
            
                                if ($status_filter) {
                                    $sql .= " WHERE status = ?";
                                    $params[] = $status_filter;
                                }
            
                                $sql .= " ORDER BY $sort_column $sort_order";
            
                                $stmt = $pdo->prepare($sql);
                                $stmt->execute($params);
                                $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
                                if (count($applications) > 0) {
                                    echo '<table class="table table-striped table-hover">';
                                    echo '<thead>';
                                    echo '<tr>';
                                    echo '<th><a href="?sort=application_id&order=' . ($sort_column == 'application_id' && $sort_order == 'ASC' ? 'DESC' : 'ASC') . '&status=' . htmlspecialchars($status_filter) . '">Application ID</a>' . getSortIcon('application_id', $sort_column, $sort_order) . '</th>';
                                    echo '<th><a href="?sort=company_name&order=' . ($sort_column == 'company_name' && $sort_order == 'ASC' ? 'DESC' : 'ASC') . '&status=' . htmlspecialchars($status_filter) . '">Company Name</a>' . getSortIcon('company_name', $sort_column, $sort_order) . '</th>';
                                    echo '<th><a href="?sort=status&order=' . ($sort_column == 'status' && $sort_order == 'ASC' ? 'DESC' : 'ASC') . '&status=' . htmlspecialchars($status_filter) . '">Status</a>' . getSortIcon('status', $sort_column, $sort_order) . '</th>';
                                    echo '<th><a href="?sort=created_at&order=' . ($sort_column == 'created_at' && $sort_order == 'ASC' ? 'DESC' : 'ASC') . '&status=' . htmlspecialchars($status_filter) . '">Date Submitted</a>' . getSortIcon('created_at', $sort_column, $sort_order) . '</th>';
                                    echo '</tr>';
                                    echo '</thead>';
                                    echo '<tbody>';
                                    foreach ($applications as $app) {                            $badgeClass = getStatusBadgeClass($app['status']);
                            echo '<tr>';
                            echo '<td><a href="view_application.php?id=' . htmlspecialchars($app['id']) . '">' . htmlspecialchars($app['application_id']) . '</a></td>';
                            echo '<td>' . htmlspecialchars($app['company_name']) . '</td>';
                            echo '<td><span class="badge ' . $badgeClass . '">' . htmlspecialchars(ucfirst(str_replace('_', ' ', $app['status']))) . '</span></td>';
                            echo '<td>' . htmlspecialchars(date("Y-m-d H:i", strtotime($app['created_at']))) . '</td>';
                            echo '</tr>';
                        }
                        echo '</tbody>';
                        echo '</table>';
                    } else {
                        echo '<p class="text-center">No customer applications found.</p>';
                    }
                } catch (PDOException $e) {
                    echo '<div class="alert alert-danger">Error: Could not fetch applications.</div>';
                    // Optional: log error to a file
                    // error_log($e->getMessage());
                }
                ?>
            </div>
        </div>
    </main>

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