﻿<?php
session_start();
require_once '../../config/database.php';

$database = new Database();
$conn = $database->getConnection();

// معالجة الفلترة والبحث
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'created_at';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';

// بناء الاستعلام
$query = "SELECT p.*, 
          COUNT(DISTINCT r.id) as rooms_count,
          COUNT(DISTINCT d.id) as devices_count
          FROM iot_projects p
          LEFT JOIN iot_project_rooms r ON p.id = r.project_id
          LEFT JOIN iot_project_devices d ON r.id = d.room_id
          WHERE 1=1";

if ($status_filter) {
    $query .= " AND p.status = :status";
}

if ($search) {
    $query .= " AND (p.customer_name LIKE :search OR p.customer_phone LIKE :search OR p.customer_email LIKE :search)";
}

$query .= " GROUP BY p.id ORDER BY p.{$sort} {$order}";

$stmt = $conn->prepare($query);

if ($status_filter) {
    $stmt->bindParam(':status', $status_filter);
}

if ($search) {
    $search_param = "%{$search}%";
    $stmt->bindParam(':search', $search_param);
}

$stmt->execute();
$projects = $stmt->fetchAll(PDO::FETCH_ASSOC);

// إحصائيات
$stats_query = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'new' THEN 1 ELSE 0 END) as new_count,
    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress_count,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_count,
    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_count,
    SUM(final_cost) as total_revenue
    FROM iot_projects";
$stats_stmt = $conn->query($stats_query);
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مقايسة مشاريع IoT</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * { font-family: 'Tajawal', sans-serif; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
        .card { 
            background: white; 
            border-radius: 20px; 
            padding: 30px; 
            box-shadow: 0 20px 60px rgba(0,0,0,0.15); 
            margin-bottom: 20px;
            border: 1px solid rgba(255,255,255,0.8);
        }
        .stat-card { 
            background: linear-gradient(135deg, #667eea, #764ba2); 
            color: white; 
            border-radius: 15px; 
            padding: 30px 25px; 
            text-align: center; 
            transition: all 0.3s;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
            border: 1px solid rgba(255,255,255,0.2);
        }
        .stat-card:hover { 
            transform: translateY(-8px); 
            box-shadow: 0 20px 50px rgba(102, 126, 234, 0.4);
        }
        .stat-card i {
            opacity: 0.9;
            filter: drop-shadow(0 4px 8px rgba(0,0,0,0.2));
        }
        .btn { 
            padding: 12px 24px; 
            border-radius: 10px; 
            font-weight: 600; 
            transition: all 0.3s; 
            cursor: pointer; 
            border: none; 
            text-decoration: none; 
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 14px;
        }
        .btn-primary { 
            background: linear-gradient(135deg, #667eea, #764ba2); 
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        .btn-secondary { 
            background: white; 
            color: #374151;
            border: 2px solid #e5e7eb;
        }
        .btn:hover { 
            transform: translateY(-2px); 
            box-shadow: 0 8px 20px rgba(0,0,0,0.15); 
        }
        .btn-primary:hover {
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }
        .form-input, .form-select { 
            width: 100%; 
            padding: 12px 16px; 
            border: 2px solid #e5e7eb; 
            border-radius: 10px; 
            transition: all 0.3s;
            background: white;
            font-size: 14px;
            font-weight: 500;
        }
        .form-input:focus, .form-select:focus { 
            outline: none; 
            border-color: #667eea; 
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
            background: #fafbff;
        }
        .form-input::placeholder {
            color: #9ca3af;
            font-weight: 400;
        }
        .data-table { 
            width: 100%; 
            border-collapse: separate;
            border-spacing: 0;
        }
        .data-table th { 
            background: linear-gradient(135deg, #f9fafb, #f3f4f6); 
            padding: 16px; 
            text-align: right; 
            font-weight: 700; 
            border-bottom: 2px solid #e5e7eb;
            color: #374151;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .data-table td { 
            padding: 16px; 
            border-bottom: 1px solid #f3f4f6;
            font-size: 14px;
        }
        .data-table tbody tr { 
            transition: all 0.2s;
        }
        .data-table tbody tr:hover { 
            background: #fafbff;
            transform: scale(1.01);
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .badge { 
            padding: 6px 14px; 
            border-radius: 20px; 
            font-size: 12px; 
            font-weight: 700; 
            display: inline-flex;
            align-items: center;
            gap: 6px;
            letter-spacing: 0.3px;
        }
        .badge-blue { background: linear-gradient(135deg, #3b82f6, #2563eb); color: white; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3); }
        .badge-green { background: linear-gradient(135deg, #10b981, #059669); color: white; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3); }
        .badge-orange { background: linear-gradient(135deg, #f59e0b, #d97706); color: white; box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3); }
        .badge-red { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3); }
        .badge-purple { background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3); }
        .btn-icon { 
            width: 38px; 
            height: 38px; 
            border-radius: 10px; 
            display: inline-flex; 
            align-items: center; 
            justify-content: center; 
            transition: all 0.3s; 
            cursor: pointer; 
            border: none;
            font-size: 14px;
        }
        .btn-icon-blue { background: linear-gradient(135deg, #3b82f6, #2563eb); color: white; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3); }
        .btn-icon-green { background: linear-gradient(135deg, #10b981, #059669); color: white; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3); }
        .btn-icon-purple { background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3); }
        .btn-icon-orange { background: linear-gradient(135deg, #f59e0b, #d97706); color: white; box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3); }
        .btn-icon-red { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3); }
        .btn-icon:hover { 
            transform: translateY(-3px) scale(1.05); 
            box-shadow: 0 6px 16px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="card">
            <div class="flex items-center justify-between flex-wrap gap-4">
                <div>
                    <h1 class="text-4xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-calculator text-purple-600 ml-3"></i>
                        مقايسة مشاريع IoT
                    </h1>
                    <p class="text-gray-600">إدارة مقايسات المنازل الذكية</p>
                </div>
                <div class="flex gap-3 flex-wrap">
                    <a href="add.php" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        مشروع جديد
                    </a>
                    <a href="templates/devices.php" class="btn btn-secondary">
                        <i class="fas fa-microchip ml-2"></i>
                        قوالب الأجهزة
                    </a>
                    <a href="templates/rooms.php" class="btn btn-secondary">
                        <i class="fas fa-door-open ml-2"></i>
                        قوالب الغرف
                    </a>
                    <a href="../iot/index.php" class="btn btn-secondary">
                        <i class="fas fa-home ml-2"></i>
                        نظام IoT
                    </a>
                </div>
            </div>
        </div>

        <!-- الإحصائيات -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div class="stat-card">
                <i class="fas fa-project-diagram text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo $stats['total']; ?></h3>
                <p class="text-sm opacity-90">إجمالي المشاريع</p>
            </div>

            <div class="stat-card">
                <i class="fas fa-file-alt text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo $stats['new_count']; ?></h3>
                <p class="text-sm opacity-90">مشاريع جديدة</p>
            </div>

            <div class="stat-card">
                <i class="fas fa-spinner text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo $stats['in_progress_count']; ?></h3>
                <p class="text-sm opacity-90">قيد التنفيذ</p>
            </div>

            <div class="stat-card">
                <i class="fas fa-check-circle text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo $stats['completed_count']; ?></h3>
                <p class="text-sm opacity-90">مكتملة</p>
            </div>

            <div class="stat-card">
                <i class="fas fa-times-circle text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo $stats['cancelled_count']; ?></h3>
                <p class="text-sm opacity-90">ملغية</p>
            </div>

            <div class="stat-card">
                <i class="fas fa-dollar-sign text-5xl mb-3"></i>
                <h3 class="text-3xl font-bold"><?php echo number_format($stats['total_revenue'], 0); ?></h3>
                <p class="text-sm opacity-90">إجمالي الإيرادات (ج.م)</p>
            </div>
        </div>

        <!-- الفلترة والبحث -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-4">
                <i class="fas fa-search text-purple-600 ml-2"></i>
                بحث وفلترة
            </h2>
            <form method="GET" class="flex flex-wrap gap-4">
            <div class="flex-1 min-w-[200px]">
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="بحث بالاسم أو الهاتف أو البريد..." 
                       class="form-input w-full">
            </div>
            
            <select name="status" class="form-select">
                <option value="">جميع الحالات</option>
                <option value="new" <?php echo $status_filter === 'new' ? 'selected' : ''; ?>>جديد</option>
                <option value="in_progress" <?php echo $status_filter === 'in_progress' ? 'selected' : ''; ?>>قيد التنفيذ</option>
                <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>مكتمل</option>
                <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>ملغي</option>
            </select>

            <select name="sort" class="form-select">
                <option value="created_at" <?php echo $sort === 'created_at' ? 'selected' : ''; ?>>تاريخ الإنشاء</option>
                <option value="final_cost" <?php echo $sort === 'final_cost' ? 'selected' : ''; ?>>التكلفة</option>
                <option value="customer_name" <?php echo $sort === 'customer_name' ? 'selected' : ''; ?>>اسم العميل</option>
            </select>

            <select name="order" class="form-select">
                <option value="DESC" <?php echo $order === 'DESC' ? 'selected' : ''; ?>>تنازلي</option>
                <option value="ASC" <?php echo $order === 'ASC' ? 'selected' : ''; ?>>تصاعدي</option>
            </select>

            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i>
                بحث
            </button>
            
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-redo"></i>
                إعادة تعيين
            </a>
        </form>
        </div>

        <!-- جدول المشاريع -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-4">
                <i class="fas fa-list text-purple-600 ml-2"></i>
                قائمة المشاريع
            </h2>
            <div class="overflow-x-auto">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>رقم المشروع</th>
                        <th>اسم العميل</th>
                        <th>الهاتف</th>
                        <th>نوع المشروع</th>
                        <th>الغرف</th>
                        <th>الأجهزة</th>
                        <th>التكلفة النهائية</th>
                        <th>الحالة</th>
                        <th>تاريخ الإنشاء</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($projects)): ?>
                        <tr>
                            <td colspan="10" class="text-center py-8 text-gray-500">
                                <i class="fas fa-inbox text-4xl mb-3"></i>
                                <p>لا توجد مشاريع حالياً</p>
                                <a href="add.php" class="btn btn-primary mt-3">
                                    <i class="fas fa-plus"></i>
                                    إضافة مشروع جديد
                                </a>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($projects as $project): ?>
                            <tr>
                                <td class="font-bold">#<?php echo $project['id']; ?></td>
                                <td><?php echo htmlspecialchars($project['customer_name']); ?></td>
                                <td dir="ltr" class="text-right"><?php echo htmlspecialchars($project['customer_phone']); ?></td>
                                <td>
                                    <?php
                                    $types = [
                                        'house' => '🏠 منزل',
                                        'apartment' => '🏢 شقة',
                                        'villa' => '🏰 فيلا',
                                        'office' => '🏢 مكتب',
                                        'other' => '📍 أخرى'
                                    ];
                                    echo $types[$project['project_type']] ?? $project['project_type'];
                                    ?>
                                </td>
                                <td>
                                    <span class="badge badge-blue">
                                        <i class="fas fa-door-open"></i>
                                        <?php echo $project['rooms_count']; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-purple">
                                        <i class="fas fa-microchip"></i>
                                        <?php echo $project['devices_count']; ?>
                                    </span>
                                </td>
                                <td class="font-bold text-green-600">
                                    <?php echo number_format($project['final_cost'], 2); ?> ج.م
                                </td>
                                <td>
                                    <?php
                                    $status_badges = [
                                        'new' => '<span class="badge badge-green">جديد</span>',
                                        'in_progress' => '<span class="badge badge-orange">قيد التنفيذ</span>',
                                        'completed' => '<span class="badge badge-blue">مكتمل</span>',
                                        'cancelled' => '<span class="badge badge-red">ملغي</span>'
                                    ];
                                    echo $status_badges[$project['status']] ?? $project['status'];
                                    ?>
                                </td>
                                <td><?php echo date('Y-m-d', strtotime($project['created_at'])); ?></td>
                                <td>
                                    <div class="flex gap-2">
                                        <a href="view.php?id=<?php echo $project['id']; ?>" 
                                           class="btn-icon btn-icon-blue" title="عرض">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="edit.php?id=<?php echo $project['id']; ?>" 
                                           class="btn-icon btn-icon-green" title="تعديل">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="rooms.php?project_id=<?php echo $project['id']; ?>" 
                                           class="btn-icon btn-icon-purple" title="الغرف">
                                            <i class="fas fa-door-open"></i>
                                        </a>
                                        <a href="print.php?id=<?php echo $project['id']; ?>" 
                                           class="btn-icon btn-icon-orange" title="طباعة" target="_blank">
                                            <i class="fas fa-print"></i>
                                        </a>
                                        <button onclick="deleteProject(<?php echo $project['id']; ?>)" 
                                                class="btn-icon btn-icon-red" title="حذف">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>

<script>
function deleteProject(id) {
    if (confirm('هل أنت متأكد من حذف هذا المشروع؟ سيتم حذف جميع الغرف والأجهزة المرتبطة به.')) {
        fetch('delete.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: id })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('تم حذف المشروع بنجاح');
                location.reload();
            } else {
                alert('حدث خطأ: ' + data.message);
            }
        })
        .catch(error => {
            alert('حدث خطأ في الاتصال');
            console.error('Error:', error);
        });
    }
}
</script>

    </div>
</body>
</html>
