<?php
/**
 * Prince VIP System - Dashboard
 * لوحة التحكم الرئيسية
 */
$pageTitle = 'لوحة التحكم';
require_once 'includes/header.php';

$db = getDB();
$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();

// ======= إحصائيات =======
if ($isAdmin) {
    // إحصائيات المدير - جميع العقود
    $totalContracts = $db->query("SELECT COUNT(*) FROM contracts")->fetchColumn();
    $activeContracts = $db->query("SELECT COUNT(*) FROM contracts WHERE status = 'active'")->fetchColumn();
    $pendingContracts = $db->query("SELECT COUNT(*) FROM contracts WHERE status = 'pending'")->fetchColumn();
    $draftContracts = $db->query("SELECT COUNT(*) FROM contracts WHERE status = 'draft'")->fetchColumn();
    $totalClients = $db->query("SELECT COUNT(*) FROM clients")->fetchColumn();
    $totalAgents = $db->query("SELECT COUNT(*) FROM users WHERE role = 'agent'")->fetchColumn();
    
    // عقود تنتهي خلال 30 يوم
    $expiringSoon = $db->query("SELECT COUNT(*) FROM contracts WHERE status = 'active' AND end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)")->fetchColumn();
    
    // آخر العقود
    $recentContracts = $db->query("SELECT c.*, cl.full_name as client_name, u.full_name as agent_name 
                                    FROM contracts c 
                                    JOIN clients cl ON c.client_id = cl.id 
                                    JOIN users u ON c.agent_id = u.id 
                                    ORDER BY c.created_at DESC LIMIT 10")->fetchAll();
} else {
    // إحصائيات الوكيل - عقوده فقط
    $stmtTotal = $db->prepare("SELECT COUNT(*) FROM contracts WHERE agent_id = ?");
    $stmtTotal->execute([$userId]);
    $totalContracts = $stmtTotal->fetchColumn();
    
    $stmtActive = $db->prepare("SELECT COUNT(*) FROM contracts WHERE agent_id = ? AND status = 'active'");
    $stmtActive->execute([$userId]);
    $activeContracts = $stmtActive->fetchColumn();
    
    $stmtPending = $db->prepare("SELECT COUNT(*) FROM contracts WHERE agent_id = ? AND status = 'pending'");
    $stmtPending->execute([$userId]);
    $pendingContracts = $stmtPending->fetchColumn();
    
    $stmtDraft = $db->prepare("SELECT COUNT(*) FROM contracts WHERE agent_id = ? AND status = 'draft'");
    $stmtDraft->execute([$userId]);
    $draftContracts = $stmtDraft->fetchColumn();
    
    $stmtClients = $db->prepare("SELECT COUNT(*) FROM clients WHERE created_by = ?");
    $stmtClients->execute([$userId]);
    $totalClients = $stmtClients->fetchColumn();
    
    $stmtExpiring = $db->prepare("SELECT COUNT(*) FROM contracts WHERE agent_id = ? AND status = 'active' AND end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)");
    $stmtExpiring->execute([$userId]);
    $expiringSoon = $stmtExpiring->fetchColumn();
    
    $stmtRecent = $db->prepare("SELECT c.*, cl.full_name as client_name, u.full_name as agent_name 
                                 FROM contracts c 
                                 JOIN clients cl ON c.client_id = cl.id 
                                 JOIN users u ON c.agent_id = u.id 
                                 WHERE c.agent_id = ?
                                 ORDER BY c.created_at DESC LIMIT 10");
    $stmtRecent->execute([$userId]);
    $recentContracts = $stmtRecent->fetchAll();
}

// حالات العقود للـ Pipeline
$statusLabels = [
    'draft' => 'مسودة',
    'pending' => 'قيد المراجعة', 
    'active' => 'نشط',
    'rejected' => 'مرفوض',
    'expired' => 'منتهي'
];
?>

<!-- Welcome Banner -->
<div class="welcome-banner">
    <div class="welcome-text">
        <h3>👋 مرحباً، <?= clean($_SESSION['full_name']) ?>!</h3>
        <p>هذا ملخص نشاطك اليوم في نظام Prince VIP</p>
    </div>
    <div class="welcome-actions">
        <a href="contract_new.php" class="btn btn-outline-light">
            <i class="fas fa-plus"></i> عقد جديد
        </a>
        <?php if ($isAdmin): ?>
        <a href="agents.php" class="btn btn-outline-light">
            <i class="fas fa-user-tie"></i> الوكلاء
        </a>
        <?php endif; ?>
        <a href="contracts.php" class="btn btn-gold">
            <i class="fas fa-file-contract"></i> العقود
        </a>
    </div>
</div>

<!-- Stat Cards -->
<div class="stat-cards">
    <div class="stat-card">
        <div class="stat-icon">📋</div>
        <div class="stat-label">إجمالي العقود</div>
        <div class="stat-value"><?= $totalContracts ?></div>
        <div class="stat-detail text-primary"><?= $activeContracts ?> عقد نشط</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">⏳</div>
        <div class="stat-label">قيد المراجعة</div>
        <div class="stat-value"><?= $pendingContracts ?></div>
        <div class="stat-detail text-warning"><?= $draftContracts ?> مسودة</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">👥</div>
        <div class="stat-label">العملاء</div>
        <div class="stat-value"><?= $totalClients ?></div>
        <div class="stat-detail text-info">إجمالي العملاء المسجلين</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">⚠️</div>
        <div class="stat-label">تنتهي قريباً</div>
        <div class="stat-value"><?= $expiringSoon ?></div>
        <div class="stat-detail text-danger">خلال 30 يوم</div>
    </div>
</div>

<?php if ($isAdmin): ?>
<!-- Agent Stats (Admin only) -->
<div class="row mb-4">
    <div class="col-12">
        <div class="content-card">
            <div class="card-header">
                <h5><i class="fas fa-user-tie text-primary"></i> إحصائيات الوكلاء</h5>
                <a href="agents.php" class="btn btn-sm btn-outline-gold">عرض الكل</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>الوكيل</th>
                                <th>إجمالي العقود</th>
                                <th>نشط</th>
                                <th>قيد المراجعة</th>
                                <th>مسودة</th>
                                <th>آخر نشاط</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $agentStats = $db->query("SELECT u.id, u.full_name, u.last_login,
                                (SELECT COUNT(*) FROM contracts WHERE agent_id = u.id) as total,
                                (SELECT COUNT(*) FROM contracts WHERE agent_id = u.id AND status = 'active') as active_count,
                                (SELECT COUNT(*) FROM contracts WHERE agent_id = u.id AND status = 'pending') as pending_count,
                                (SELECT COUNT(*) FROM contracts WHERE agent_id = u.id AND status = 'draft') as draft_count
                                FROM users u WHERE u.role = 'agent' AND u.is_active = 1 ORDER BY total DESC")->fetchAll();
                            
                            foreach ($agentStats as $agent):
                            ?>
                            <tr>
                                <td class="fw-bold"><?= clean($agent['full_name']) ?></td>
                                <td><?= $agent['total'] ?></td>
                                <td><span class="status-badge active"><?= $agent['active_count'] ?></span></td>
                                <td><span class="status-badge pending"><?= $agent['pending_count'] ?></span></td>
                                <td><span class="status-badge draft"><?= $agent['draft_count'] ?></span></td>
                                <td class="text-muted small"><?= $agent['last_login'] ? date('Y/m/d H:i', strtotime($agent['last_login'])) : 'لم يسجل دخول' ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($agentStats)): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">لا يوجد وكلاء مسجلين</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Pipeline View -->
<div class="content-card">
    <div class="card-header">
        <h5><i class="fas fa-columns text-primary"></i> خط سير العقود</h5>
        <a href="contract_new.php" class="btn btn-gold btn-sm">
            <i class="fas fa-plus"></i> عقد جديد
        </a>
    </div>
    <div class="card-body">
        <div class="pipeline-container">
            <?php
            $statuses = ['draft', 'pending', 'active', 'rejected'];
            $statusColors = ['draft' => '#6c757d', 'pending' => '#ffc107', 'active' => '#28a745', 'rejected' => '#dc3545'];
            
            foreach ($statuses as $status):
                if ($isAdmin) {
                    $pipeStmt = $db->prepare("SELECT c.*, cl.full_name as client_name FROM contracts c JOIN clients cl ON c.client_id = cl.id WHERE c.status = ? ORDER BY c.created_at DESC LIMIT 5");
                } else {
                    $pipeStmt = $db->prepare("SELECT c.*, cl.full_name as client_name FROM contracts c JOIN clients cl ON c.client_id = cl.id WHERE c.status = ? AND c.agent_id = ? ORDER BY c.created_at DESC LIMIT 5");
                }
                
                if ($isAdmin) {
                    $pipeStmt->execute([$status]);
                } else {
                    $pipeStmt->execute([$status, $userId]);
                }
                $pipeContracts = $pipeStmt->fetchAll();
                
                // عد العقود في هذه الحالة
                if ($isAdmin) {
                    $countStmt = $db->prepare("SELECT COUNT(*) FROM contracts WHERE status = ?");
                    $countStmt->execute([$status]);
                } else {
                    $countStmt = $db->prepare("SELECT COUNT(*) FROM contracts WHERE status = ? AND agent_id = ?");
                    $countStmt->execute([$status, $userId]);
                }
                $statusCount = $countStmt->fetchColumn();
            ?>
            <div class="pipeline-column">
                <div class="column-header">
                    <h6><?= $statusLabels[$status] ?></h6>
                    <span class="count" style="background:<?= $statusColors[$status] ?>"><?= $statusCount ?></span>
                </div>
                
                <?php if (empty($pipeContracts)): ?>
                <div class="text-center text-muted small py-4">
                    <i class="fas fa-inbox d-block mb-2" style="font-size:1.5rem;opacity:0.3;"></i>
                    لا توجد عقود
                </div>
                <?php else: ?>
                <?php foreach ($pipeContracts as $contract): ?>
                <div class="pipeline-card" style="border-right-color:<?= $statusColors[$status] ?>">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="card-name"><?= clean($contract['client_name']) ?></div>
                        <span class="status-badge <?= $status ?>"><?= $statusLabels[$status] ?></span>
                    </div>
                    <div class="card-company"><?= clean($contract['car_type'] ?? '-') ?> - <?= clean($contract['car_number'] ?? '-') ?></div>
                    <div class="card-info">
                        <i class="fas fa-hashtag"></i> <?= clean($contract['contract_number']) ?>
                    </div>
                    <div class="card-info">
                        <i class="fas fa-calendar"></i> <?= $contract['start_date'] ?> → <?= $contract['end_date'] ?>
                    </div>
                    <div class="card-actions">
                        <a href="contract_view.php?id=<?= $contract['id'] ?>" class="btn btn-sm btn-outline-gold">
                            <i class="fas fa-eye"></i> عرض
                        </a>
                        <?php if ($contract['status'] === 'active'): ?>
                        <a href="policy_pdf.php?id=<?= $contract['id'] ?>" class="btn btn-sm btn-gold" target="_blank">
                            <i class="fas fa-file-pdf"></i> بوليصة
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Recent Contracts Table -->
<div class="content-card">
    <div class="card-header">
        <h5><i class="fas fa-clock text-warning"></i> آخر العقود</h5>
        <a href="contracts.php" class="btn btn-sm btn-outline-gold">عرض الكل</a>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>رقم العقد</th>
                        <th>العميل</th>
                        <?php if ($isAdmin): ?><th>الوكيل</th><?php endif; ?>
                        <th>نوع السيارة</th>
                        <th>رقم السيارة</th>
                        <th>تاريخ البدء</th>
                        <th>تاريخ الانتهاء</th>
                        <th>الحالة</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentContracts as $contract): ?>
                    <tr>
                        <td class="fw-bold"><?= clean($contract['contract_number']) ?></td>
                        <td><?= clean($contract['client_name']) ?></td>
                        <?php if ($isAdmin): ?><td class="text-muted"><?= clean($contract['agent_name']) ?></td><?php endif; ?>
                        <td><?= clean($contract['car_type'] ?? '-') ?></td>
                        <td><?= clean($contract['car_number'] ?? '-') ?></td>
                        <td><?= $contract['start_date'] ?></td>
                        <td><?= $contract['end_date'] ?></td>
                        <td><span class="status-badge <?= $contract['status'] ?>"><?= $statusLabels[$contract['status']] ?></span></td>
                        <td>
                            <a href="contract_view.php?id=<?= $contract['id'] ?>" class="btn btn-sm btn-outline-gold" data-bs-toggle="tooltip" title="عرض">
                                <i class="fas fa-eye"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($recentContracts)): ?>
                    <tr><td colspan="<?= $isAdmin ? 9 : 8 ?>" class="text-center text-muted py-4">لا توجد عقود بعد</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
