<?php
$pageTitle = 'Applications';
require_once dirname(__DIR__) . '/includes/header.php';

// Create table if not exists
db()->query("CREATE TABLE IF NOT EXISTS applications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(100) NOT NULL,
    mobile VARCHAR(30) NOT NULL,
    email VARCHAR(150),
    country VARCHAR(100),
    education VARCHAR(100),
    grad_year VARCHAR(10),
    gpa VARCHAR(20),
    english_test VARCHAR(30),
    message TEXT,
    status ENUM('new','contacted','processing','completed','rejected') DEFAULT 'new',
    is_read TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Delete
if (isset($_GET['delete'])) {
    db()->query("DELETE FROM applications WHERE id=".(int)$_GET['delete']);
    flash('Application deleted.','success');
    redirect(ADMIN_URL.'/pages/applications.php');
}

// Update status
if (isset($_POST['update_status'])) {
    $aid = (int)$_POST['app_id'];
    $st  = trim($_POST['status'] ?? 'new');
    db()->query("UPDATE applications SET status='".db()->real_escape_string($st)."', is_read=1 WHERE id=$aid");
    flash('Status updated!','success');
    redirect(ADMIN_URL.'/pages/applications.php');
}

// View single - mark read
$viewing = null;
if (isset($_GET['view'])) {
    $aid = (int)$_GET['view'];
    $viewing = db()->query("SELECT * FROM applications WHERE id=$aid")->fetch_assoc();
    if ($viewing) db()->query("UPDATE applications SET is_read=1 WHERE id=$aid");
}

$filter = $_GET['filter'] ?? 'all';
$where  = $filter !== 'all' ? "WHERE status='".db()->real_escape_string($filter)."'" : "";
$apps   = db()->query("SELECT * FROM applications $where ORDER BY created_at DESC")->fetch_all(MYSQLI_ASSOC);
$unread = db()->query("SELECT COUNT(*) as c FROM applications WHERE is_read=0")->fetch_assoc()['c'] ?? 0;
$total  = db()->query("SELECT COUNT(*) as c FROM applications")->fetch_assoc()['c'] ?? 0;

$statusColors = ['new'=>'badge-blue','contacted'=>'badge-yellow','processing'=>'badge-yellow','completed'=>'badge-green','rejected'=>'badge-red'];
$statusLabels = ['new'=>'New','contacted'=>'Contacted','processing'=>'Processing','completed'=>'Completed','rejected'=>'Rejected'];
?>

<div class="page-header">
    <h1>Applications
        <?php if($unread>0): ?><span class="badge badge-red" style="font-size:13px;margin-left:6px"><?=$unread?> new</span><?php endif; ?>
    </h1>
    <div class="page-header-actions" style="display:flex;gap:8px;flex-wrap:wrap">
        <?php foreach(['all'=>'All','new'=>'New','contacted'=>'Contacted','processing'=>'Processing','completed'=>'Completed','rejected'=>'Rejected'] as $k=>$v): ?>
        <a href="?filter=<?=$k?>" class="btn btn-sm <?=$filter===$k?'btn-primary':'btn-secondary'?>"><?=$v?></a>
        <?php endforeach; ?>
    </div>
</div>

<!-- Stats Row -->
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:12px;margin-bottom:20px">
    <?php
    $statQ = db()->query("SELECT status, COUNT(*) as c FROM applications GROUP BY status");
    $counts = ['new'=>0,'contacted'=>0,'processing'=>0,'completed'=>0,'rejected'=>0];
    while($r=$statQ->fetch_assoc()) $counts[$r['status']]=$r['c'];
    $statDef = [
        'total'      => ['label'=>'Total','count'=>$total,'icon'=>'fa-file-alt','bg'=>'#dbeafe','color'=>'#1e40af'],
        'new'        => ['label'=>'New','count'=>$counts['new'],'icon'=>'fa-star','bg'=>'#dbeafe','color'=>'#1e40af'],
        'contacted'  => ['label'=>'Contacted','count'=>$counts['contacted'],'icon'=>'fa-phone','bg'=>'#fef3c7','color'=>'#92400e'],
        'processing' => ['label'=>'Processing','count'=>$counts['processing'],'icon'=>'fa-cog','bg'=>'#ede9fe','color'=>'#5b21b6'],
        'completed'  => ['label'=>'Completed','count'=>$counts['completed'],'icon'=>'fa-check-circle','bg'=>'#d1fae5','color'=>'#065f46'],
        'rejected'   => ['label'=>'Rejected','count'=>$counts['rejected'],'icon'=>'fa-times-circle','bg'=>'#fee2e2','color'=>'#991b1b'],
    ];
    foreach($statDef as $s): ?>
    <div class="card" style="padding:14px;display:flex;align-items:center;gap:12px">
        <div style="width:38px;height:38px;border-radius:10px;background:<?=$s['bg']?>;color:<?=$s['color']?>;display:grid;place-items:center;font-size:16px;flex-shrink:0">
            <i class="fas <?=$s['icon']?>"></i>
        </div>
        <div>
            <div style="font-size:22px;font-weight:700;line-height:1"><?=$s['count']?></div>
            <div style="font-size:11px;color:var(--muted);margin-top:2px"><?=$s['label']?></div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php if ($viewing): ?>
<!-- Single View -->
<div class="card" style="margin-bottom:20px;border:2px solid var(--brand)">
    <div class="card-header">
        <i class="fas fa-user" style="color:var(--brand)"></i>
        <h2><?=htmlspecialchars($viewing['full_name'])?>'s Application</h2>
        <div class="card-actions">
            <a href="applications.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Back</a>
            <button onclick="confirmDelete('applications.php?delete=<?=$viewing['id']?>','this application')" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>
        </div>
    </div>
    <div class="card-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:14px;background:#f9fafb;border-radius:10px;padding:18px;margin-bottom:18px">
            <?php $fields = ['full_name'=>'Full Name','mobile'=>'Mobile','email'=>'Email','country'=>'Country','education'=>'Education','grad_year'=>'Graduation Year','gpa'=>'GPA/CGPA','english_test'=>'English Test'];
            foreach($fields as $k=>$label): if(empty($viewing[$k])) continue; ?>
            <div>
                <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px"><?=$label?></div>
                <div style="font-weight:600"><?=htmlspecialchars($viewing[$k])?></div>
            </div>
            <?php endforeach; ?>
            <div>
                <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px">Applied</div>
                <div style="font-weight:600"><?=date('M j, Y g:i A',strtotime($viewing['created_at']))?></div>
            </div>
        </div>
        <?php if($viewing['message']): ?>
        <div style="background:#fff;border:1px solid var(--border);border-radius:8px;padding:16px;margin-bottom:16px">
            <div style="font-size:12px;color:var(--muted);margin-bottom:6px">Message</div>
            <p style="line-height:1.7"><?=nl2br(htmlspecialchars($viewing['message']))?></p>
        </div>
        <?php endif; ?>
        <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
            <form method="POST" style="display:flex;gap:8px;align-items:center">
                <input type="hidden" name="app_id" value="<?=$viewing['id']?>">
                <select name="status" class="form-select" style="width:160px">
                    <?php foreach($statusLabels as $k=>$v): ?>
                    <option value="<?=$k?>" <?=$viewing['status']===$k?'selected':''?>><?=$v?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" name="update_status" class="btn btn-primary btn-sm"><i class="fas fa-save"></i> Update</button>
            </form>
            <?php if($viewing['mobile']): ?>
            <a href="tel:<?=htmlspecialchars($viewing['mobile'])?>" class="btn btn-secondary btn-sm"><i class="fas fa-phone"></i> Call</a>
            <a href="https://wa.me/<?=preg_replace('/\D/','',$viewing['mobile'])?>" target="_blank" class="btn btn-secondary btn-sm" style="color:#25d366"><i class="fab fa-whatsapp"></i> WhatsApp</a>
            <?php endif; ?>
            <?php if($viewing['email']): ?>
            <a href="mailto:<?=htmlspecialchars($viewing['email'])?>" class="btn btn-secondary btn-sm"><i class="fas fa-envelope"></i> Email</a>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- List -->
<div class="card">
    <div class="card-header">
        <i class="fas fa-inbox" style="color:var(--brand)"></i>
        <h2>All Applications</h2>
        <span style="color:var(--muted);font-size:13px;margin-left:auto"><?=count($apps)?> shown</span>
    </div>
    <div class="table-wrap">
        <?php if(empty($apps)): ?>
        <div style="padding:48px;text-align:center;color:var(--muted)">
            <i class="fas fa-inbox" style="font-size:36px;opacity:.3;display:block;margin-bottom:12px"></i>
            No applications <?=$filter!=='all'?"with status '$filter'":'yet'?>.
        </div>
        <?php else: ?>
        <table>
            <thead><tr><th></th><th>Name</th><th>Mobile</th><th>Country</th><th>Education</th><th>Status</th><th>Date</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($apps as $a): ?>
            <tr style="<?=!$a['is_read']?'background:#fffbeb;font-weight:600':''?>">
                <td><?=!$a['is_read']?'<span style="width:8px;height:8px;background:var(--brand);border-radius:50%;display:inline-block"></span>':''?></td>
                <td><?=htmlspecialchars($a['full_name'])?></td>
                <td style="font-size:13px"><?=htmlspecialchars($a['mobile'])?></td>
                <td><?=htmlspecialchars($a['country'])?></td>
                <td style="font-size:13px;color:var(--muted)"><?=htmlspecialchars($a['education'])?></td>
                <td><span class="badge <?=$statusColors[$a['status']]??'badge-blue'?>"><?=$statusLabels[$a['status']]??ucfirst($a['status'])?></span></td>
                <td style="font-size:12px;color:var(--muted);white-space:nowrap"><?=date('M j, Y',strtotime($a['created_at']))?></td>
                <td>
                    <div style="display:flex;gap:5px">
                        <a href="?view=<?=$a['id']?>" class="btn btn-secondary btn-sm btn-icon" title="View"><i class="fas fa-eye"></i></a>
                        <?php if($a['mobile']): ?><a href="https://wa.me/<?=preg_replace('/\D/','',$a['mobile'])?>" target="_blank" class="btn btn-secondary btn-sm btn-icon" title="WhatsApp" style="color:#25d366"><i class="fab fa-whatsapp"></i></a><?php endif; ?>
                        <button onclick="confirmDelete('applications.php?delete=<?=$a['id']?>','<?=htmlspecialchars(addslashes($a['full_name']))?>')" class="btn btn-danger btn-sm btn-icon"><i class="fas fa-trash"></i></button>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>
<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
