﻿<?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;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_name = trim($_POST['customer_name']);
    $customer_phone = trim($_POST['customer_phone']);
    $customer_email = trim($_POST['customer_email']);
    $project_type = $_POST['project_type'];
    $status = $_POST['status'];
    $discount_percentage = floatval($_POST['discount_percentage']);
    $notes = trim($_POST['notes']);
    
    if (empty($customer_name) || empty($customer_phone)) {
        $error = 'الرجاء إدخال اسم العميل ورقم الهاتف';
    } else {
        try {
            $query = "UPDATE iot_projects SET 
                      customer_name = :customer_name,
                      customer_phone = :customer_phone,
                      customer_email = :customer_email,
                      project_type = :project_type,
                      status = :status,
                      discount_percentage = :discount_percentage,
                      notes = :notes
                      WHERE id = :id";
            
            $stmt = $conn->prepare($query);
            $stmt->bindParam(':customer_name', $customer_name);
            $stmt->bindParam(':customer_phone', $customer_phone);
            $stmt->bindParam(':customer_email', $customer_email);
            $stmt->bindParam(':project_type', $project_type);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':discount_percentage', $discount_percentage);
            $stmt->bindParam(':notes', $notes);
            $stmt->bindParam(':id', $project_id);
            
            if ($stmt->execute()) {
                $success = 'تم تحديث المشروع بنجاح';
                // إعادة جلب البيانات المحدثة
                $stmt = $conn->prepare("SELECT * FROM iot_projects WHERE id = :id");
                $stmt->bindParam(':id', $project_id);
                $stmt->execute();
                $project = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $error = 'حدث خطأ أثناء تحديث المشروع';
            }
        } catch (PDOException $e) {
            $error = 'خطأ في قاعدة البيانات: ' . $e->getMessage();
        }
    }
}

?>
<!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="view.php?id=<?php echo $project_id; ?>" class="btn btn-secondary">
                <i class="fas fa-eye"></i>
                عرض المشروع
            </a>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-arrow-right"></i>
                العودة
            </a>
        </div>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-error mb-6">
            <i class="fas fa-exclamation-circle"></i>
            <?php echo $error; ?>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success mb-6">
            <i class="fas fa-check-circle"></i>
            <?php echo $success; ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <form method="POST" class="space-y-6">
            <!-- معلومات العميل -->
            <div class="border-b pb-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-user text-blue-500"></i>
                    معلومات العميل
                </h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="form-label required">اسم العميل</label>
                        <input type="text" name="customer_name" required 
                               value="<?php echo htmlspecialchars($project['customer_name']); ?>"
                               class="form-input">
                    </div>

                    <div>
                        <label class="form-label required">رقم الهاتف</label>
                        <input type="tel" name="customer_phone" required 
                               value="<?php echo htmlspecialchars($project['customer_phone']); ?>"
                               class="form-input" pattern="[0-9]{10}" dir="ltr">
                    </div>

                    <div>
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" name="customer_email" 
                               value="<?php echo htmlspecialchars($project['customer_email']); ?>"
                               class="form-input" dir="ltr">
                    </div>

                    <div>
                        <label class="form-label required">نوع المشروع</label>
                        <select name="project_type" required class="form-select">
                            <option value="house" <?php echo $project['project_type'] === 'house' ? 'selected' : ''; ?>>🏠 منزل</option>
                            <option value="apartment" <?php echo $project['project_type'] === 'apartment' ? 'selected' : ''; ?>>🏢 شقة</option>
                            <option value="villa" <?php echo $project['project_type'] === 'villa' ? 'selected' : ''; ?>>🏰 فيلا</option>
                            <option value="office" <?php echo $project['project_type'] === 'office' ? 'selected' : ''; ?>>🏢 مكتب</option>
                            <option value="other" <?php echo $project['project_type'] === 'other' ? 'selected' : ''; ?>>📍 أخرى</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- حالة المشروع والخصم -->
            <div class="border-b pb-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-cog text-purple-500"></i>
                    إعدادات المشروع
                </h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="form-label required">حالة المشروع</label>
                        <select name="status" required class="form-select">
                            <option value="new" <?php echo $project['status'] === 'new' ? 'selected' : ''; ?>>
                                🆕 جديد
                            </option>
                            <option value="in_progress" <?php echo $project['status'] === 'in_progress' ? 'selected' : ''; ?>>
                                ⏳ قيد التنفيذ
                            </option>
                            <option value="completed" <?php echo $project['status'] === 'completed' ? 'selected' : ''; ?>>
                                ✅ مكتمل
                            </option>
                            <option value="cancelled" <?php echo $project['status'] === 'cancelled' ? 'selected' : ''; ?>>
                                ❌ ملغي
                            </option>
                        </select>
                    </div>

                    <div>
                        <label class="form-label">نسبة الخصم (%)</label>
                        <input type="number" name="discount_percentage" step="0.01" min="0" max="100"
                               value="<?php echo $project['discount_percentage']; ?>"
                               class="form-input" placeholder="0.00">
                        <small class="text-gray-500">سيتم تطبيق الخصم على التكلفة الإجمالية</small>
                    </div>
                </div>
            </div>

            <!-- ملاحظات -->
            <div>
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-sticky-note text-yellow-500"></i>
                    ملاحظات إضافية
                </h2>
                
                <textarea name="notes" rows="4" class="form-input"><?php echo htmlspecialchars($project['notes']); ?></textarea>
            </div>

            <!-- معلومات إضافية -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="font-bold text-gray-700 mb-2">معلومات المشروع:</h3>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    <div>
                        <p class="text-gray-600">تاريخ الإنشاء:</p>
                        <p class="font-bold"><?php echo date('Y-m-d', strtotime($project['created_at'])); ?></p>
                    </div>
                    <div>
                        <p class="text-gray-600">آخر تحديث:</p>
                        <p class="font-bold"><?php echo date('Y-m-d', strtotime($project['updated_at'])); ?></p>
                    </div>
                    <div>
                        <p class="text-gray-600">التكلفة الإجمالية:</p>
                        <p class="font-bold text-green-600"><?php echo number_format($project['total_cost'], 2); ?> ج.م</p>
                    </div>
                    <div>
                        <p class="text-gray-600">التكلفة النهائية:</p>
                        <p class="font-bold text-blue-600"><?php echo number_format($project['final_cost'], 2); ?> ج.م</p>
                    </div>
                </div>
            </div>

            <!-- أزرار الإجراءات -->
            <div class="flex gap-4 pt-6 border-t">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i>
                    حفظ التعديلات
                </button>
                
                <a href="view.php?id=<?php echo $project_id; ?>" class="btn btn-secondary">
                    <i class="fas fa-times"></i>
                    إلغاء
                </a>

                <a href="rooms.php?project_id=<?php echo $project_id; ?>" class="btn btn-secondary">
                    <i class="fas fa-door-open"></i>
                    إدارة الغرف
                </a>
            </div>
        </form>
    </div>
        </div>
    </div>

<style>
.form-label.required::after {
    content: ' *';
    color: #ef4444;
}
</style>

</body>
</html>
