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

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

$project_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($project_id <= 0) {
    header('Location: index.php');
    exit;
}

// جلب معلومات المشروع
$query = "SELECT * FROM iot_projects WHERE id = :id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':id', $project_id);
$stmt->execute();
$project = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$project) {
    header('Location: index.php');
    exit;
}

// جلب الغرف والأجهزة
$rooms_query = "SELECT r.*, 
                (SELECT COUNT(*) FROM iot_project_devices WHERE room_id = r.id) as devices_count,
                (SELECT SUM(total_price) FROM iot_project_devices WHERE room_id = r.id) as room_cost
                FROM iot_project_rooms r
                WHERE r.project_id = :project_id
                ORDER BY r.created_at ASC";
$rooms_stmt = $conn->prepare($rooms_query);
$rooms_stmt->bindParam(':project_id', $project_id);
$rooms_stmt->execute();
$rooms = $rooms_stmt->fetchAll(PDO::FETCH_ASSOC);

// حساب التكلفة الإجمالية
$total_cost = 0;
foreach ($rooms as $room) {
    $total_cost += $room['room_cost'] ?? 0;
}

// حساب الخصم والتكلفة النهائية
$discount_amount = ($total_cost * $project['discount_percentage']) / 100;
$final_cost = $total_cost - $discount_amount;

// تحديث التكلفة في قاعدة البيانات
$update_query = "UPDATE iot_projects SET total_cost = :total_cost, discount_amount = :discount_amount, final_cost = :final_cost WHERE id = :id";
$update_stmt = $conn->prepare($update_query);
$update_stmt->bindParam(':total_cost', $total_cost);
$update_stmt->bindParam(':discount_amount', $discount_amount);
$update_stmt->bindParam(':final_cost', $final_cost);
$update_stmt->bindParam(':id', $project_id);
$update_stmt->execute();

?>
<!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">
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <div class="container">
        <div class="main-content">
    <div class="content-header">
        <div>
            <h1 class="text-3xl font-bold text-gray-800">📋 عرض المشروع</h1>
            <p class="text-gray-600 mt-2">مشروع #<?php echo $project['id']; ?></p>
        </div>
        <div class="flex gap-3">
            <a href="blueprint.php?id=<?php echo $project_id; ?>" class="btn btn-success">
                <i class="fas fa-drafting-compass"></i>
                كروكي 2D
            </a>
            <a href="print.php?id=<?php echo $project_id; ?>" class="btn btn-primary" target="_blank">
                <i class="fas fa-print"></i>
                طباعة المقايسة
            </a>
            <a href="edit.php?id=<?php echo $project_id; ?>" class="btn btn-secondary">
                <i class="fas fa-edit"></i>
                تعديل
            </a>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-arrow-right"></i>
                العودة
            </a>
        </div>
    </div>

    <!-- معلومات المشروع -->
    <div class="card mb-6">
        <div class="flex justify-between items-start mb-6">
            <div>
                <h2 class="text-2xl font-bold text-gray-800 mb-2">
                    <?php echo htmlspecialchars($project['customer_name']); ?>
                </h2>
                <div class="space-y-1 text-gray-600">
                    <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($project['customer_phone']); ?></p>
                    <?php if ($project['customer_email']): ?>
                        <p><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($project['customer_email']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
            <div class="text-left">
                <?php
                $status_badges = [
                    'new' => '<span class="badge badge-green text-lg">جديد</span>',
                    'in_progress' => '<span class="badge badge-orange text-lg">قيد التنفيذ</span>',
                    'completed' => '<span class="badge badge-blue text-lg">مكتمل</span>',
                    'cancelled' => '<span class="badge badge-red text-lg">ملغي</span>'
                ];
                echo $status_badges[$project['status']] ?? $project['status'];
                ?>
                <p class="text-sm text-gray-600 mt-2">
                    تاريخ الإنشاء: <?php echo date('Y-m-d', strtotime($project['created_at'])); ?>
                </p>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
            <div>
                <p class="text-sm text-gray-600">نوع المشروع</p>
                <p class="font-bold">
                    <?php
                    $types = [
                        'house' => '🏠 منزل',
                        'apartment' => '🏢 شقة',
                        'villa' => '🏰 فيلا',
                        'office' => '🏢 مكتب',
                        'other' => '📍 أخرى'
                    ];
                    echo $types[$project['project_type']] ?? $project['project_type'];
                    ?>
                </p>
            </div>
            <div>
                <p class="text-sm text-gray-600">عدد الغرف</p>
                <p class="font-bold"><?php echo count($rooms); ?> غرفة</p>
            </div>
        </div>

        <?php if ($project['notes']): ?>
            <div class="mt-4 p-4 bg-yellow-50 rounded-lg">
                <p class="text-sm font-bold text-gray-700 mb-1">
                    <i class="fas fa-sticky-note text-yellow-600"></i>
                    ملاحظات:
                </p>
                <p class="text-gray-700"><?php echo nl2br(htmlspecialchars($project['notes'])); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <!-- الغرف والأجهزة -->
    <?php if (empty($rooms)): ?>
        <div class="card text-center py-12">
            <i class="fas fa-door-open text-6xl text-gray-300 mb-4"></i>
            <p class="text-xl text-gray-600 mb-4">لم يتم إضافة أي غرف بعد</p>
            <a href="rooms.php?project_id=<?php echo $project_id; ?>" class="btn btn-primary">
                <i class="fas fa-plus"></i>
                إضافة غرف
            </a>
        </div>
    <?php else: ?>
        <?php foreach ($rooms as $index => $room): ?>
            <?php
            // جلب أجهزة الغرفة
            $devices_query = "SELECT * FROM iot_project_devices WHERE room_id = :room_id ORDER BY device_type";
            $devices_stmt = $conn->prepare($devices_query);
            $devices_stmt->bindParam(':room_id', $room['id']);
            $devices_stmt->execute();
            $devices = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);
            ?>
            
            <div class="card mb-6">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-xl font-bold text-gray-800">
                            <?php
                            $room_icons = [
                                'bedroom' => '🛏️',
                                'living_room' => '🛋️',
                                'kitchen' => '🍳',
                                'bathroom' => '🚿',
                                'office' => '💼',
                                'garage' => '🚗',
                                'garden' => '🌳',
                                'other' => '📍'
                            ];
                            echo $room_icons[$room['room_type']] ?? '📍';
                            ?>
                            <?php echo htmlspecialchars($room['room_name']); ?>
                        </h3>
                        <?php if ($room['area_sqm']): ?>
                            <p class="text-sm text-gray-600">
                                <i class="fas fa-ruler-combined"></i>
                                المساحة: <?php echo $room['area_sqm']; ?> م²
                            </p>
                        <?php endif; ?>
                    </div>
                    <div class="text-left">
                        <p class="text-2xl font-bold text-green-600">
                            <?php echo number_format($room['room_cost'] ?? 0, 2); ?> ج.م
                        </p>
                        <p class="text-sm text-gray-600"><?php echo count($devices); ?> جهاز</p>
                    </div>
                </div>

                <?php if (empty($devices)): ?>
                    <div class="text-center py-8 bg-gray-50 rounded-lg">
                        <p class="text-gray-500">لم يتم إضافة أجهزة لهذه الغرفة</p>
                        <a href="devices.php?room_id=<?php echo $room['id']; ?>" class="btn btn-sm btn-primary mt-3">
                            <i class="fas fa-plus"></i>
                            إضافة أجهزة
                        </a>
                    </div>
                <?php else: ?>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-2 text-right">الجهاز</th>
                                    <th class="px-4 py-2 text-center">الكمية</th>
                                    <th class="px-4 py-2 text-center">سعر الوحدة</th>
                                    <th class="px-4 py-2 text-center">تكلفة التركيب</th>
                                    <th class="px-4 py-2 text-center">الإجمالي</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($devices as $device): ?>
                                    <tr class="border-t">
                                        <td class="px-4 py-3">
                                            <p class="font-bold"><?php echo htmlspecialchars($device['device_name']); ?></p>
                                            <?php if ($device['device_model']): ?>
                                                <p class="text-sm text-gray-600"><?php echo htmlspecialchars($device['device_model']); ?></p>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-4 py-3 text-center"><?php echo $device['quantity']; ?></td>
                                        <td class="px-4 py-3 text-center"><?php echo number_format($device['unit_price'], 2); ?> ج.م</td>
                                        <td class="px-4 py-3 text-center"><?php echo number_format($device['installation_cost'], 2); ?> ج.م</td>
                                        <td class="px-4 py-3 text-center font-bold text-green-600">
                                            <?php echo number_format($device['total_price'], 2); ?> ج.م
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>

        <!-- ملخص التكلفة -->
        <div class="card bg-gradient-to-br from-blue-50 to-purple-50">
            <h3 class="text-xl font-bold text-gray-800 mb-4">
                <i class="fas fa-calculator text-blue-600"></i>
                ملخص التكلفة
            </h3>
            
            <div class="space-y-3">
                <div class="flex justify-between items-center pb-3 border-b">
                    <span class="text-gray-700">التكلفة الإجمالية:</span>
                    <span class="text-xl font-bold"><?php echo number_format($total_cost, 2); ?> ج.م</span>
                </div>
                
                <?php if ($project['discount_percentage'] > 0): ?>
                    <div class="flex justify-between items-center pb-3 border-b">
                        <span class="text-gray-700">الخصم (<?php echo $project['discount_percentage']; ?>%):</span>
                        <span class="text-xl font-bold text-red-600">- <?php echo number_format($discount_amount, 2); ?> ج.م</span>
                    </div>
                <?php endif; ?>
                
                <div class="flex justify-between items-center pt-3">
                    <span class="text-xl font-bold text-gray-800">التكلفة النهائية:</span>
                    <span class="text-3xl font-bold text-green-600"><?php echo number_format($final_cost, 2); ?> ج.م</span>
                </div>
            </div>
        </div>
    <?php endif; ?>
        </div>
    </div>
</body>
</html>
