﻿<?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) {
    die('معرف المشروع غير صحيح');
}

// جلب معلومات المشروع
$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) {
    die('المشروع غير موجود');
}

// جلب الغرف والأجهزة
$rooms_query = "SELECT r.* 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);
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>عرض سعر #<?php echo str_pad($project['id'], 5, '0', STR_PAD_LEFT); ?> - <?php echo htmlspecialchars($project['customer_name']); ?></title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700;800&display=swap');
        
        @page {
            size: A4;
            margin: 0;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Cairo', 'Segoe UI', Tahoma, sans-serif;
            line-height: 1.8;
            color: #2d3748;
            background: white;
            padding: 0;
        }
        
        .container {
            max-width: 210mm;
            margin: 0 auto;
            background: white;
            padding: 20mm;
        }
        
        /* Header with Company Logo */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding-bottom: 30px;
            border-bottom: 4px solid #667eea;
            margin-bottom: 40px;
        }
        
        .company-info {
            flex: 1;
        }
        
        .company-logo {
            width: 120px;
            height: 120px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 48px;
            font-weight: 800;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }
        
        .company-name {
            font-size: 28px;
            font-weight: 800;
            color: #1a202c;
            margin-bottom: 8px;
            letter-spacing: -0.5px;
        }
        
        .company-tagline {
            color: #718096;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .company-details {
            font-size: 12px;
            color: #4a5568;
            line-height: 1.8;
        }
        
        .company-details i {
            color: #667eea;
            width: 16px;
            display: inline-block;
        }
        
        /* Document Title */
        .doc-title {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
        }
        
        .doc-title h1 {
            font-size: 26px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .doc-title .doc-number {
            font-size: 14px;
            opacity: 0.9;
        }
        
        /* Client Info Box */
        .client-info-box {
            background: #f7fafc;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 30px;
        }
        
        .client-info-header {
            font-size: 16px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #cbd5e0;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .info-item {
            display: flex;
            align-items: baseline;
        }
        
        .info-label {
            font-weight: 600;
            color: #4a5568;
            min-width: 120px;
            font-size: 13px;
        }
        
        .info-value {
            color: #1a202c;
            font-weight: 500;
            font-size: 14px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-new { background: #c6f6d5; color: #22543d; }
        .status-progress { background: #feebc8; color: #7c2d12; }
        .status-completed { background: #bee3f8; color: #2c5282; }
        .status-cancelled { background: #fed7d7; color: #742a2a; }
        
        /* Room Sections */
        .room-section {
            margin-bottom: 25px;
            page-break-inside: avoid;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            overflow: hidden;
        }
        
        .room-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 18px 25px;
            font-size: 18px;
            font-weight: 700;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .room-header .room-icon {
            font-size: 24px;
            margin-left: 10px;
        }
        
        /* Devices Table */
        .devices-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }
        
        .devices-table thead {
            background: #f7fafc;
        }
        
        .devices-table th {
            padding: 14px 16px;
            text-align: right;
            border-bottom: 2px solid #cbd5e0;
            font-weight: 700;
            font-size: 12px;
            color: #4a5568;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .devices-table td {
            padding: 14px 16px;
            border-bottom: 1px solid #e2e8f0;
            font-size: 13px;
        }
        
        .devices-table tbody tr:hover {
            background: #f7fafc;
        }
        
        .devices-table .device-name {
            font-weight: 600;
            color: #2d3748;
        }
        
        .devices-table .device-model {
            font-size: 11px;
            color: #718096;
            margin-top: 2px;
        }
        
        .devices-table .price-cell {
            font-weight: 600;
            color: #2d3748;
            text-align: center;
        }
        
        .devices-table .total-cell {
            font-weight: 700;
            color: #38a169;
            font-size: 14px;
        }
        
        .room-total {
            background: #edf2f7;
            padding: 15px 25px;
            font-weight: 700;
            color: #2d3748;
            font-size: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .room-total-amount {
            color: #38a169;
            font-size: 18px;
        }
        
        /* Summary Section */
        .summary {
            margin-top: 40px;
            background: white;
            border: 3px solid #667eea;
            border-radius: 12px;
            overflow: hidden;
            page-break-inside: avoid;
        }
        
        .summary-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            font-size: 20px;
            font-weight: 700;
        }
        
        .summary-body {
            padding: 30px;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 15px 0;
            border-bottom: 2px solid #e2e8f0;
            font-size: 15px;
        }
        
        .summary-item:last-child {
            border-bottom: none;
            margin-top: 15px;
            padding-top: 25px;
            border-top: 3px solid #667eea;
        }
        
        .summary-label {
            font-weight: 600;
            color: #4a5568;
        }
        
        .summary-value {
            font-weight: 700;
            color: #2d3748;
            font-size: 16px;
        }
        
        .summary-item:last-child .summary-label {
            font-size: 20px;
            color: #1a202c;
        }
        
        .summary-item:last-child .summary-value {
            font-size: 28px;
            color: #38a169;
        }
        
        .discount-value {
            color: #e53e3e !important;
        }
        
        /* Notes Section */
        .notes {
            margin: 30px 0;
            padding: 20px 25px;
            background: #fffbeb;
            border-right: 5px solid #f59e0b;
            border-radius: 8px;
        }
        
        .notes-header {
            font-weight: 700;
            color: #92400e;
            margin-bottom: 10px;
            font-size: 15px;
        }
        
        .notes-content {
            color: #78350f;
            line-height: 1.8;
            font-size: 13px;
        }
        
        /* Terms & Conditions */
        .terms {
            margin-top: 40px;
            padding: 25px;
            background: #f7fafc;
            border-radius: 12px;
            page-break-inside: avoid;
        }
        
        .terms-header {
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 15px;
            font-size: 16px;
            border-bottom: 2px solid #cbd5e0;
            padding-bottom: 10px;
        }
        
        .terms-list {
            list-style: none;
            padding: 0;
        }
        
        .terms-list li {
            padding: 8px 0;
            padding-right: 25px;
            position: relative;
            color: #4a5568;
            font-size: 13px;
            line-height: 1.8;
        }
        
        .terms-list li:before {
            content: "✓";
            position: absolute;
            right: 0;
            color: #38a169;
            font-weight: bold;
        }
        
        /* Footer */
        .footer {
            margin-top: 50px;
            padding-top: 30px;
            border-top: 3px solid #e2e8f0;
            text-align: center;
        }
        
        .footer-content {
            color: #718096;
            font-size: 12px;
            line-height: 2;
        }
        
        .footer-highlight {
            color: #667eea;
            font-weight: 700;
            font-size: 14px;
        }
        
        .validity-notice {
            background: #edf2f7;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            color: #4a5568;
            font-size: 12px;
        }
        
        @media print {
            body {
                padding: 0;
            }
            
            .no-print {
                display: none;
            }
            
            .room-section {
                page-break-inside: avoid;
            }
        }
        
        .print-button {
            position: fixed;
            top: 20px;
            left: 20px;
            padding: 12px 24px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            z-index: 1000;
        }
        
        .print-button:hover {
            background: #764ba2;
        }
    </style>
</head>
<body>
    <button onclick="window.print()" class="print-button no-print">
        🖨️ طباعة المقايسة
    </button>

    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="company-info">
                <div class="company-name">Smart Home Solutions</div>
                <div class="company-tagline">حلول المنازل الذكية المتكاملة</div>
                <div class="company-details">
                    <div><i class="fas fa-phone"></i> +20 123 456 7890</div>
                    <div><i class="fas fa-envelope"></i> info@smarthome.eg</div>
                    <div><i class="fas fa-map-marker-alt"></i> القاهرة، مصر</div>
                </div>
            </div>
            <div class="company-logo">
                <i class="fas fa-home"></i>
            </div>
        </div>

        <!-- Document Title -->
        <div class="doc-title">
            <h1>عرض سعر - مشروع منزل ذكي</h1>
            <div class="doc-number">رقم العرض: #<?php echo str_pad($project['id'], 5, '0', STR_PAD_LEFT); ?> | تاريخ الإصدار: <?php echo date('d/m/Y'); ?></div>
        </div>

        <!-- Client Info -->
        <div class="client-info-box">
            <div class="client-info-header">معلومات العميل</div>
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">اسم العميل:</span>
                    <span class="info-value"><?php echo htmlspecialchars($project['customer_name']); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">رقم الهاتف:</span>
                    <span class="info-value"><?php echo htmlspecialchars($project['customer_phone']); ?></span>
                </div>
                <?php if ($project['customer_email']): ?>
                <div class="info-item">
                    <span class="info-label">البريد الإلكتروني:</span>
                    <span class="info-value"><?php echo htmlspecialchars($project['customer_email']); ?></span>
                </div>
                <?php endif; ?>
                <div class="info-item">
                    <span class="info-label">نوع المشروع:</span>
                    <span class="info-value">
                        <?php
                        $types = [
                            'house' => 'منزل',
                            'apartment' => 'شقة',
                            'villa' => 'فيلا',
                            'office' => 'مكتب',
                            'other' => 'أخرى'
                        ];
                        echo $types[$project['project_type']] ?? $project['project_type'];
                        ?>
                    </span>
                </div>
                <div class="info-item">
                    <span class="info-label">تاريخ الإنشاء:</span>
                    <span class="info-value"><?php echo date('d/m/Y', strtotime($project['created_at'])); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">حالة العرض:</span>
                    <span class="info-value">
                        <?php
                        $status_classes = [
                            'new' => 'status-new',
                            'in_progress' => 'status-progress',
                            'completed' => 'status-completed',
                            'cancelled' => 'status-cancelled'
                        ];
                        $statuses = [
                            'new' => 'جديد',
                            'in_progress' => 'قيد التنفيذ',
                            'completed' => 'مكتمل',
                            'cancelled' => 'ملغي'
                        ];
                        $status_class = $status_classes[$project['status']] ?? '';
                        $status_text = $statuses[$project['status']] ?? $project['status'];
                        ?>
                        <span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                    </span>
                </div>
            </div>
        </div>

        <?php if ($project['notes']): ?>
        <div class="notes">
            <div class="notes-header">📝 ملاحظات خاصة بالمشروع</div>
            <div class="notes-content"><?php echo nl2br(htmlspecialchars($project['notes'])); ?></div>
        </div>
        <?php endif; ?>

        <!-- Rooms and Devices -->
        <?php
        $total_cost = 0;
        foreach ($rooms as $room):
            // جلب أجهزة الغرفة
            $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);
            
            $room_cost = array_sum(array_column($devices, 'total_price'));
            $total_cost += $room_cost;
        ?>
        
        <div class="room-section">
            <div class="room-header">
                <div>
                    <span class="room-icon">
                        <?php
                        $room_icons = [
                            'bedroom' => '🛏️',
                            'living_room' => '🛋️',
                            'kitchen' => '🍳',
                            'bathroom' => '🚿',
                            'office' => '💼',
                            'garage' => '🚗',
                            'garden' => '🌳',
                            'other' => '📍'
                        ];
                        echo $room_icons[$room['room_type']] ?? '📍';
                        ?>
                    </span>
                    <?php echo htmlspecialchars($room['room_name']); ?>
                    <?php if ($room['area_sqm']): ?>
                        <span style="font-size: 14px; opacity: 0.9;">(<?php echo $room['area_sqm']; ?> م²)</span>
                    <?php endif; ?>
                </div>
                <div style="font-size: 14px; opacity: 0.9;">
                    <?php echo count($devices); ?> جهاز
                </div>
            </div>
            
            <?php if (!empty($devices)): ?>
            <table class="devices-table">
                <thead>
                    <tr>
                        <th style="width: 5%">#</th>
                        <th style="width: 40%">البند</th>
                        <th style="width: 10%">الكمية</th>
                        <th style="width: 15%">سعر الوحدة</th>
                        <th style="width: 15%">التركيب</th>
                        <th style="width: 15%">الإجمالي</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($devices as $index => $device): ?>
                    <tr>
                        <td style="text-align: center; color: #718096;"><?php echo $index + 1; ?></td>
                        <td>
                            <div class="device-name"><?php echo htmlspecialchars($device['device_name']); ?></div>
                            <?php if ($device['device_model']): ?>
                                <div class="device-model"><?php echo htmlspecialchars($device['device_model']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="price-cell"><?php echo $device['quantity']; ?></td>
                        <td class="price-cell"><?php echo number_format($device['unit_price'], 2); ?> ج.م</td>
                        <td class="price-cell"><?php echo number_format($device['installation_cost'], 2); ?> ج.م</td>
                        <td class="price-cell total-cell">
                            <?php echo number_format($device['total_price'], 2); ?> ج.م
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div class="room-total">
                <span>إجمالي تكلفة الغرفة:</span>
                <span class="room-total-amount"><?php echo number_format($room_cost, 2); ?> ج.م</span>
            </div>
            <?php else: ?>
            <p style="padding: 30px; text-align: center; color: #a0aec0;">لم يتم إضافة أجهزة لهذه الغرفة</p>
            <?php endif; ?>
        </div>
        
        <?php endforeach; ?>

        <!-- Summary -->
        <div class="summary">
            <div class="summary-header">💰 ملخص التكلفة الإجمالية</div>
            <div class="summary-body">
                <div class="summary-item">
                    <span class="summary-label">التكلفة الإجمالية:</span>
                    <span class="summary-value"><?php echo number_format($total_cost, 2); ?> ج.م</span>
                </div>
                <?php if ($project['discount_percentage'] > 0): ?>
                <div class="summary-item">
                    <span class="summary-label">الخصم (<?php echo $project['discount_percentage']; ?>%):</span>
                    <span class="summary-value discount-value">- <?php echo number_format($project['discount_amount'], 2); ?> ج.م</span>
                </div>
                <?php endif; ?>
                <div class="summary-item">
                    <span class="summary-label">المبلغ الإجمالي المستحق:</span>
                    <span class="summary-value"><?php echo number_format($project['final_cost'], 2); ?> ج.م</span>
                </div>
            </div>
        </div>

        <!-- Terms & Conditions -->
        <div class="terms">
            <div class="terms-header">الشروط والأحكام</div>
            <ul class="terms-list">
                <li>هذا العرض صالح لمدة 30 يوماً من تاريخ الإصدار</li>
                <li>الأسعار المذكورة شاملة ضريبة القيمة المضافة</li>
                <li>يتم الدفع على دفعتين: 50% عند بدء التنفيذ و 50% عند الانتهاء</li>
                <li>مدة التنفيذ المتوقعة: من 7 إلى 14 يوم عمل حسب حجم المشروع</li>
                <li>ضمان سنة على جميع الأجهزة والتركيبات</li>
                <li>صيانة مجانية لمدة 3 أشهر بعد التسليم</li>
                <li>تدريب مجاني على استخدام النظام</li>
            </ul>
        </div>

        <!-- Footer -->
        <div class="footer">
            <div class="footer-content">
                <p class="footer-highlight">شكراً لثقتكم بنا</p>
                <p>نحن في خدمتكم دائماً لتقديم أفضل حلول المنازل الذكية</p>
                <p>للاستفسارات: +20 123 456 7890 | info@smarthome.eg</p>
            </div>
            <div class="validity-notice">
                <strong>ملاحظة:</strong> هذا عرض سعر غير ملزم ويخضع للتعديل حسب المتطلبات النهائية للمشروع
            </div>
        </div>
    </div>

    <script>
        // طباعة تلقائية عند فتح الصفحة (اختياري)
        // window.onload = function() { window.print(); }
    </script>
</body>
</html>
