<?php
session_start();
require_once '../includes/db_config.php';

if (!isset($_SESSION['staff_id'])) {
    header('Location: ../login.php');
    exit;
}

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM delivery_staff WHERE id = ?");
    $stmt->execute([$_SESSION['staff_id']]);
    $staff = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$staff) {
        session_destroy();
        header('Location: ../login.php');
        exit;
    }
    
    $stmt = $pdo->prepare("
        SELECT o.*, u.name as customer_name 
        FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id 
        WHERE o.status IN ('pending', 'processing', 'ready') 
        ORDER BY o.created_at DESC 
        LIMIT 10
    ");
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("
        SELECT o.*, u.name as customer_name 
        FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id 
        WHERE o.status = 'delivered' AND o.delivery_staff_id = ?
        ORDER BY o.delivered_at DESC 
        LIMIT 20
    ");
    $stmt->execute([$_SESSION['staff_id']]);
    $delivered_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $today = date('Y-m-d');
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as today_deliveries 
        FROM orders 
        WHERE DATE(delivered_at) = ? AND status = 'delivered' AND delivery_staff_id = ?
    ");
    $stmt->execute([$today, $_SESSION['staff_id']]);
    $today_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "Database error: " . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $new_status = $_POST['status'];
    $location = $_POST['location'] ?? '';
    
    try {
        $stmt = $pdo->prepare("UPDATE delivery_staff SET status = ?, current_location = ? WHERE id = ?");
        $stmt->execute([$new_status, $location, $_SESSION['staff_id']]);
        $_SESSION['staff_status'] = $new_status;
        $_SESSION['success_message'] = "Status updated successfully";
        header('Location: dashboard.php');
        exit;
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error updating status";
        header('Location: dashboard.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order_status'])) {
    $order_id = $_POST['order_id'];
    $new_order_status = $_POST['order_status'];
    
    try {
        $stmt = $pdo->prepare("SELECT user_id, id, status FROM orders WHERE id = ?");
        $stmt->execute([$order_id]);
        $order_info = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($new_order_status === 'processing') {
            $stmt = $pdo->prepare("UPDATE orders SET status = ?, processing_started_at = NOW(), updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_order_status, $order_id]);
        } elseif ($new_order_status === 'ready') {
            $stmt = $pdo->prepare("UPDATE orders SET status = ?, ready_at = NOW(), updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_order_status, $order_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$new_order_status, $order_id]);
        }
        
        $current_time = date('Y-m-d H:i');
        
        if ($new_order_status === 'processing') {
            $notification_title = 'Order Received';
            $notification_message = "Your order #" . $order_id . " has been received and processing has started.\nTime: " . $current_time;
            $stmt = $pdo->prepare("INSERT INTO notifications (title, message, type, user_id, created_at) VALUES (?, ?, 'info', ?, NOW())");
            $stmt->execute([$notification_title, $notification_message, $order_info['user_id']]);
        }
        
        if ($new_order_status === 'ready') {
            $notification_title = 'Your Order is Ready for Delivery!';
            $notification_message = "Your order #" . $order_id . " is now ready and will be delivered soon.\nTime: " . $current_time;
            $stmt = $pdo->prepare("INSERT INTO notifications (title, message, type, user_id, created_at) VALUES (?, ?, 'success', ?, NOW())");
            $stmt->execute([$notification_title, $notification_message, $order_info['user_id']]);
        }
        
        $_SESSION['success_message'] = "Order status updated successfully";
        header('Location: dashboard.php');
        exit;
        
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error updating order status: " . $e->getMessage();
        header('Location: dashboard.php');
        exit;
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ../login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delivery Dashboard - Allura Dry Clean</title>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="Map.js" defer></script>
</head>
<body class="delivery-dashboard">
    <header class="delivery-header">
        <div class="logo">
            <img src="../img/logo.png" alt="Allura Logo">
        </div>
        
        <div class="staff-info">
            <h2>Welcome, <?php echo htmlspecialchars($staff['name']); ?></h2>
            <p><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($staff['email']); ?></p>
        </div>
        
        <a href="?logout=1" class="logout-btn">
            <i class="fas fa-sign-out-alt"></i>
            Logout
        </a>
    </header>

    <div class="delivery-container">
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="delivery-success-message">
                <i class="fas fa-check-circle"></i>
                <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="delivery-error-message">
                <i class="fas fa-exclamation-triangle"></i>
                <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            </div>
        <?php endif; ?>

        <div class="delivery-stats-grid">
            <div class="delivery-stat-card <?php echo $staff['status']; ?>">
                <div class="icon">
                    <?php 
                    $icons = [
                        'available' => 'fas fa-check-circle',
                        'busy' => 'fas fa-clock',
                        'offline' => 'fas fa-times-circle'
                    ];
                    echo '<i class="' . $icons[$staff['status']] . '"></i>';
                    ?>
                </div>
                <h3><?php 
                    $status_text = [
                        'available' => 'Available',
                        'busy' => 'Busy',
                        'offline' => 'Offline'
                    ];
                    echo $status_text[$staff['status']];
                ?></h3>
                <p>Current Status</p>
            </div>
            
            <div class="delivery-stat-card deliveries">
                <div class="icon">
                    <i class="fas fa-truck"></i>
                </div>
                <h3><?php echo $staff['total_deliveries']; ?></h3>
                <p>Total Deliveries</p>
            </div>
            
            <div class="delivery-stat-card deliveries">
                <div class="icon">
                    <i class="fas fa-star"></i>
                </div>
                <h3><?php echo number_format($staff['rating'], 1); ?></h3>
                <p>Rating</p>
            </div>
            
            <div class="delivery-stat-card deliveries">
                <div class="icon">
                    <i class="fas fa-calendar-day"></i>
                </div>
                <h3><?php echo $today_stats['today_deliveries']; ?></h3>
                <p>Today's Deliveries</p>
            </div>
        </div>

        <div class="delivery-section">
            <h3><i class="fas fa-edit"></i> Update Status & Location</h3>
            <form method="POST" class="delivery-form">
                <div class="form-group">
                    <label for="status">Status:</label>
                    <select name="status" id="status" required>
                        <option value="available" <?php echo $staff['status'] === 'available' ? 'selected' : ''; ?>>Available</option>
                        <option value="busy" <?php echo $staff['status'] === 'busy' ? 'selected' : ''; ?>>Busy</option>
                        <option value="offline" <?php echo $staff['status'] === 'offline' ? 'selected' : ''; ?>>Offline</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="location">Current Location:</label>
                    <input type="text" name="location" id="location" 
                           value="<?php echo htmlspecialchars($staff['current_location'] ?? ''); ?>"
                           placeholder="Enter your current location">
                </div>
                
                <button type="submit" name="update_status" class="btnD">
                    <i class="fas fa-save"></i>
                    Update
                </button>
            </form>
        </div>

        <div class="delivery-section">
            <h3><i class="fas fa-list"></i> Recent Orders</h3>
            
            <?php if (empty($orders)): ?>
                <p style="text-align: center; color: #666; padding: 40px;">
                    <i class="fas fa-inbox" style="font-size: 48px; display: block; margin-bottom: 15px;"></i>
                    No orders available
                </p>
            <?php else: ?>
                <table class="delivery-orders-table">
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer</th>
                            <th>Amount</th>
                            <th>Delivery Date</th>
                            <th>Status</th>
                            <th>Phone</th>
                            <th>Location</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>#<?php echo $order['id']; ?></td>
                            <td><?php echo htmlspecialchars($order['customer_name'] ?: $order['customer_name']); ?></td>
                            <td>SAR <?php echo number_format($order['total_amount'], 2); ?></td>
                            <td><?php echo date('Y-m-d', strtotime($order['delivery_date'])); ?></td>
                            <td>
                                <span class="delivery-status-badge delivery-status-<?php echo $order['status']; ?>">
                                    <?php 
                                    $status_ar = [
                                        'pending' => 'Pending',
                                        'processing' => 'Processing',
                                        'ready' => 'Ready',
                                        'delivered' => 'Delivered'
                                    ];
                                    echo $status_ar[$order['status']];
                                    ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($order['customer_phone']); ?></td>
                            <td>
                                <?php 
                                $location_data = $order['customer_location'] ? json_decode($order['customer_location'], true) : null;
                                if ($location_data && $order['status'] === 'processing'): 
                                ?>
                                    <div class="location-info">
                                        <button onclick="showLocationModal(<?php echo $location_data['latitude']; ?>, <?php echo $location_data['longitude']; ?>, '<?php echo htmlspecialchars($location_data['address'] ?? ''); ?>')" class="location-btn">
                                            <i class="fas fa-map-marker-alt"></i> View Location
                                        </button>
                                        <small><?php echo date('H:i', strtotime($location_data['updated_at'])); ?></small>
                                    </div>
                                <?php elseif ($order['status'] === 'processing'): ?>
                                    <span class="no-location">
                                        <i class="fas fa-exclamation-triangle"></i> The customer did not specify his location.
                                    </span>
                                <?php else: ?>
                                    <span class="location-na">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($order['status'] === 'pending'): ?>
                                    <button onclick="pickupOrder(<?php echo $order['id']; ?>)" class="delivery-action-btn pickup">
                                        <i class="fas fa-hand-holding"></i> Pickup Order
                                    </button>
                                <?php elseif ($order['status'] === 'ready'): ?>
                                    <button onclick="showCodeModal(<?php echo $order['id']; ?>)" class="delivery-action-btn delivered">
                                        <i class="fas fa-check"></i> Mark Delivered
                                    </button>
                                <?php elseif ($order['status'] === 'processing'): ?>
                                    <button onclick="notifyCustomerArrival(<?php echo $order['id']; ?>)" class="delivery-action-btn notify" style="margin-bottom: 5px;">
                                        <i class="fas fa-bell"></i> Notify Arrival
                                    </button>
                                    <button onclick="updateOrderStatus(<?php echo $order['id']; ?>, 'ready')" class="delivery-action-btn">
                                        <i class="fas fa-box"></i> Mark Ready
                                    </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <!-- Delivered Orders Section -->
        <div class="delivery-section" style="margin-top: 30px;">
            <h3><i class="fas fa-check-circle"></i> Delivered Orders</h3>
            <?php if (empty($delivered_orders)): ?>
                <p style="text-align: center; color: #666; padding: 40px;">
                    <i class="fas fa-box-open" style="font-size: 48px; display: block; margin-bottom: 15px;"></i>
                    No delivered orders yet
                </p>
            <?php else: ?>
                <table class="delivery-orders-table">
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer</th>
                            <th>Amount</th>
                            <th>Order Date</th>
                            <th>Delivered Date</th>
                            <th>Phone</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($delivered_orders as $order): ?>
                        <tr>
                            <td>#<?php echo $order['id']; ?></td>
                            <td><?php echo htmlspecialchars($order['customer_name'] ?: 'N/A'); ?></td>
                            <td>SAR <?php echo number_format($order['total_amount'], 2); ?></td>
                            <td><?php echo date('Y-m-d', strtotime($order['created_at'])); ?></td>
                            <td>
                                <strong><?php echo date('Y-m-d H:i', strtotime($order['delivered_at'])); ?></strong>
                            </td>
                            <td><?php echo htmlspecialchars($order['customer_phone']); ?></td>
                            <td>
                                <span class="delivery-status-badge delivery-status-delivered">
                                    <i class="fas fa-check-circle"></i> Delivered
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <!-- Code Verification Modal -->
    <div id="codeModal" class="code-modal" style="display: none;">
        <div class="code-modal-content">
            <div class="code-modal-header">
                <h3><i class="fas fa-lock"></i> Enter Code</h3>
                <span class="code-modal-close" onclick="closeCodeModal()">&times;</span>
            </div>
            <div class="code-modal-body">
                <p>Enter the code from customer:</p>
                <input type="text" id="codeInput" maxlength="6" placeholder="000000" inputmode="numeric" pattern="[0-9]*">
                <div class="code-modal-actions">
                    <button onclick="verifyCode()" class="code-action-btn primary">
                        <i class="fas fa-check"></i> Verify
                    </button>
                    <button onclick="closeCodeModal()" class="code-action-btn secondary">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Location Modal -->
    <div id="locationModal" class="location-modal" style="display: none;">
        <div class="location-modal-content">
            <div class="location-modal-header">
                <h3><i class="fas fa-map-marker-alt"></i> Customer Location</h3>
                <span class="location-modal-close" onclick="closeLocationModal()">&times;</span>
            </div>
            <div class="location-modal-body">
                <div id="locationAddress" class="location-address"></div>
                <div id="locationMap" class="location-map" style="height: 400px; border-radius: 8px; margin: 15px 0;"></div>
                <div class="location-actions">
                    <button id="openGoogleMaps" class="location-action-btn primary" target="_blank">
                        <i class="fas fa-external-link-alt"></i> Open in Google Maps
                    </button>
                    <button id="getDirections" class="location-action-btn secondary" target="_blank">
                        <i class="fas fa-route"></i> Get Directions
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../js/delivery.js"></script>
</body>
</html>
