<?php
// driver_update.php

require_once 'db_config.php';

// معالجة طلب التحديث (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $token = $input['token'] ?? '';
    $status = $input['status'] ?? '';
    $notes = $input['notes'] ?? '';

    if (empty($token) || empty($status)) {
        http_response_code(400);
        echo json_encode(["error" => "بيانات غير مكتملة"]);
        exit;
    }

    $stmt = $db->prepare("SELECT id, data FROM mixers WHERE driver_token = ?");
    $stmt->execute([$token]);
    $mixer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$mixer) {
        http_response_code(404);
        echo json_encode(["error" => "رابط غير صالح أو توكن غير موجود"]);
        exit;
    }

    // Update SQL columns
    $updateStmt = $db->prepare("UPDATE mixers SET status = ?, breakdown_notes = ? WHERE driver_token = ?");
    $updateStmt->execute([$status, $notes, $token]);

    // Update JSON data to keep ERP in sync
    $jsonData = json_decode($mixer['data'], true);
    if (is_array($jsonData)) {
        $jsonData['status'] = $status;
        if ($status === 'maintenance' || $status === 'inactive') {
            // Note: The user requested "ملاحظات العطل", we map it to "notes" field in JSON which maps to "mixer-notes" in HTML
            $jsonData['notes'] = $notes;
        } else {
            $jsonData['notes'] = ''; // Clear notes if active
        }
        $updateJson = $db->prepare("UPDATE mixers SET data = ? WHERE id = ?");
        $updateJson->execute([json_encode($jsonData), $mixer['id']]);
    }

    echo json_encode(["success" => true, "message" => "تم تحديث حالة الخلاطة بنجاح!"]);
    exit;
}

// عرض واجهة المستخدم (GET)
$token = $_GET['token'] ?? '';

if (empty($token)) {
    die("<div style='text-align:center; padding:50px; font-family:sans-serif; color:red;'><h2>رابط غير صالح!</h2><p>يرجى التأكد من الرابط المرسل لك.</p></div>");
}

$stmt = $db->prepare("SELECT id, data, status, breakdown_notes FROM mixers WHERE driver_token = ?");
$stmt->execute([$token]);
$mixer = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$mixer) {
    die("<div style='text-align:center; padding:50px; font-family:sans-serif; color:red;'><h2>رابط غير صالح!</h2><p>الرابط المستخدم غير موجود أو تم تغييره.</p></div>");
}

$mixerData = json_decode($mixer['data'], true);
$mixerName = isset($mixerData['code']) ? $mixerData['code'] : 'خلاطة #' . $mixer['id'];
$currentStatus = $mixer['status'] ?? 'active';
$currentNotes = $mixer['breakdown_notes'] ?? '';

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تحديث حالة الخلاطة</title>
    <style>
        :root {
            --primary: #2c3e50;
            --success: #27ae60;
            --danger: #e74c3c;
            --bg: #f4f7f6;
            --card: #ffffff;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--bg);
            margin: 0;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .container {
            background-color: var(--card);
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.1);
            padding: 30px;
            width: 100%;
            max-width: 400px;
            text-align: center;
        }
        h2 {
            color: var(--primary);
            margin-top: 0;
            margin-bottom: 5px;
        }
        .mixer-badge {
            display: inline-block;
            background: #eef2f5;
            color: var(--primary);
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 1.2rem;
            margin-bottom: 25px;
            border: 1px solid #dcdcdc;
        }
        .status-btn {
            display: block;
            width: 100%;
            padding: 15px;
            font-size: 1.1rem;
            font-weight: bold;
            border: none;
            border-radius: 8px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-sizing: border-box;
            border: 2px solid transparent;
        }
        .btn-active {
            background-color: var(--success);
            color: white;
        }
        .btn-inactive {
            background-color: var(--danger);
            color: white;
        }
        .status-btn.selected {
            border: 3px solid #000;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
            transform: scale(1.02);
        }
        .status-btn:not(.selected) {
            opacity: 0.6;
        }
        
        #notes-container {
            text-align: right;
            margin-top: 20px;
            display: <?php echo ($currentStatus !== 'active') ? 'block' : 'none'; ?>;
            animation: fadeIn 0.3s;
        }
        label {
            display: block;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }
        textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 8px;
            resize: vertical;
            min-height: 80px;
            font-family: inherit;
            box-sizing: border-box;
        }
        .submit-btn {
            background-color: var(--primary);
            color: white;
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 8px;
            font-size: 1.2rem;
            font-weight: bold;
            margin-top: 25px;
            cursor: pointer;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .submit-btn:hover {
            background-color: #1a252f;
        }
        
        /* Overlay Loading */
        #loading {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255,255,255,0.9);
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .spinner {
            border: 5px solid #f3f3f3;
            border-top: 5px solid var(--primary);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        
        #success-msg {
            display: none;
            background: var(--success);
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <div id="loading">
        <div class="spinner"></div>
        <h3 style="margin-top:15px; color:var(--primary);">جاري التحديث...</h3>
    </div>

    <div class="container">
        <h2>تحديث حالة الخلاطة</h2>
        <div class="mixer-badge"><?php echo htmlspecialchars($mixerName); ?></div>

        <button type="button" class="status-btn btn-active <?php echo ($currentStatus === 'active') ? 'selected' : ''; ?>" onclick="selectStatus('active')">
            🟢 الخلاطة تعمل
        </button>
        <button type="button" class="status-btn btn-inactive <?php echo ($currentStatus !== 'active') ? 'selected' : ''; ?>" onclick="selectStatus('maintenance')">
            🔴 الخلاطة معطلة / صيانة
        </button>

        <div id="notes-container">
            <label for="breakdown_notes">تفاصيل العطل أو الملاحظات:</label>
            <textarea id="breakdown_notes" placeholder="اكتب ما حدث باختصار..."><?php echo htmlspecialchars($currentNotes); ?></textarea>
        </div>

        <button type="button" class="submit-btn" onclick="submitUpdate()">حفظ التحديث ✅</button>
        
        <div id="success-msg">تم التحديث بنجاح! سيتم إخطار الإدارة فوراً.</div>
    </div>

    <script>
        const token = "<?php echo htmlspecialchars($token); ?>";
        let currentStatus = "<?php echo htmlspecialchars($currentStatus === 'active' ? 'active' : 'maintenance'); ?>";

        function selectStatus(status) {
            currentStatus = status;
            
            // Update UI buttons
            document.querySelectorAll('.status-btn').forEach(btn => btn.classList.remove('selected'));
            if (status === 'active') {
                document.querySelector('.btn-active').classList.add('selected');
                document.getElementById('notes-container').style.display = 'none';
            } else {
                document.querySelector('.btn-inactive').classList.add('selected');
                document.getElementById('notes-container').style.display = 'block';
            }
        }

        async function submitUpdate() {
            const notes = document.getElementById('breakdown_notes').value;
            
            if (currentStatus !== 'active' && notes.trim() === '') {
                alert("الرجاء كتابة تفاصيل العطل أو الملاحظات!");
                return;
            }

            document.getElementById('loading').style.display = 'flex';
            document.getElementById('success-msg').style.display = 'none';

            try {
                const response = await fetch('driver_update.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        token: token,
                        status: currentStatus,
                        notes: notes
                    })
                });

                const data = await response.json();

                if (response.ok && data.success) {
                    document.getElementById('success-msg').style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('success-msg').style.display = 'none';
                    }, 5000);
                } else {
                    alert(data.error || "حدث خطأ أثناء التحديث!");
                }
            } catch (error) {
                alert("خطأ في الاتصال بالسيرفر!");
            } finally {
                document.getElementById('loading').style.display = 'none';
            }
        }
    </script>
</body>
</html>
