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

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

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM laundry_staff WHERE id = ?");
    $stmt->execute([$_SESSION['laundry_staff_id']]);
    $staff = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$staff) {
        session_destroy();
        header('Location: ../login.php');
        exit;
    }
    
    $stmt = $pdo->prepare("
        SELECT o.*, 
               COALESCE(o.customer_name, u.name) as customer_name,
               u.phone as customer_phone_db,
               GROUP_CONCAT(s.name SEPARATOR ', ') as service_names,
               GROUP_CONCAT(oi.quantity SEPARATOR ', ') as quantities,
               GROUP_CONCAT(DISTINCT s.category SEPARATOR ',') as service_categories,
               MAX(CASE WHEN s.category = 'subscription' THEN 1 ELSE 0 END) as is_subscription
        FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id 
        LEFT JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN services s ON oi.service_id = s.id
        GROUP BY o.id
        ORDER BY o.created_at DESC
    ");
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $today = date('Y-m-d');
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = ?");
    $stmt->execute([$today]);
    $today_orders = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE status = 'pending'");
    $stmt->execute();
    $pending_orders = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE status = 'processing'");
    $stmt->execute();
    $processing_orders = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE status = 'ready'");
    $stmt->execute();
    $ready_orders = $stmt->fetch()['count'];
    
} catch (PDOException $e) {
    $error = "Database error: " . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order_status'])) {
    $order_id = $_POST['order_id'];
    $new_status = $_POST['order_status'];
    
    try {
       
        $stmt = $pdo->prepare("
            SELECT o.user_id, 
                   MAX(CASE WHEN s.category = 'subscription' THEN 1 ELSE 0 END) as is_subscription
            FROM orders o
            LEFT JOIN order_items oi ON o.id = oi.order_id
            LEFT JOIN services s ON oi.service_id = s.id
            WHERE o.id = ?
            GROUP BY o.id
        ");
        $stmt->execute([$order_id]);
        $order_info = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($order_info && $order_info['is_subscription'] == 1) {
            $_SESSION['error_message'] = "Cannot update subscription orders - they are auto-activated";
            header('Location: dashboard.php');
            exit;
        }
        
        $stmt = $pdo->prepare("UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$new_status, $order_id]);
        
        $status_messages = [
            'pending' => 'Your order is pending confirmation',
            'processing' => 'Your order is being processed',
            'ready' => 'Your order is ready for delivery'
        ];
        
        if (isset($status_messages[$new_status]) && $order_info['user_id']) {
            $notification_title = 'Order Status Updated';
            $notification_message = "Order #" . $order_id . ": " . $status_messages[$new_status];
            $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']]);
        }
        
        $_SESSION['success_message'] = "Order status updated successfully";
        header('Location: dashboard.php');
        exit;
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error updating order status";
        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>Laundry Staff Dashboard - Allura Dry Clean</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
</head>
<body>
    <div class="laundry-container">
        <div class="laundry-header">
            <div>
                <h1><i class="fas fa-tshirt"></i> Laundry Staff Dashboard</h1>
            </div>
            <div class="laundry-user-info">
                <span class="laundry-user-name">
                    <i class="fas fa-user"></i> <?php echo htmlspecialchars($staff['name']); ?>
                </span>
                <a href="?logout=1" class="laundry-logout-btn">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>

        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="laundry-alert laundry-alert-success">
                <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="laundry-alert laundry-alert-error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            </div>
        <?php endif; ?>

        <div class="laundry-stats-grid">
            <div class="laundry-stat-card laundry-stat-today">
                <i class="fas fa-calendar-day"></i>
                <h3><?php echo $today_orders; ?></h3>
                <p>Today's Orders</p>
            </div>
            <div class="laundry-stat-card laundry-stat-pending">
                <i class="fas fa-clock"></i>
                <h3><?php echo $pending_orders; ?></h3>
                <p>Pending Orders</p>
            </div>
            <div class="laundry-stat-card laundry-stat-processing">
                <i class="fas fa-spinner"></i>
                <h3><?php echo $processing_orders; ?></h3>
                <p>Processing Orders</p>
            </div>
            <div class="laundry-stat-card laundry-stat-ready">
                <i class="fas fa-check-circle"></i>
                <h3><?php echo $ready_orders; ?></h3>
                <p>Ready for Delivery</p>
            </div>
        </div>

        <div class="laundry-orders-section">
            <h2><i class="fas fa-list"></i> All Orders</h2>
            
            <?php if (count($orders) > 0): ?>
                <table class="laundry-orders-table">
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer</th>
                            <th>Services</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order): ?>
                            <tr>
                                <td><strong>#<?php echo $order['id']; ?></strong></td>
                                <td>
                                    <?php echo htmlspecialchars($order['customer_name']); ?>
                                    <div class="laundry-order-details">
                                        <i class="fas fa-phone"></i> 
                                        <?php echo htmlspecialchars($order['customer_phone'] ?: $order['customer_phone_db']); ?>
                                    </div>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($order['service_names'] ?: 'N/A'); ?>
                                    <?php if ($order['quantities']): ?>
                                        <div class="laundry-order-details">Qty: <?php echo htmlspecialchars($order['quantities']); ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><strong>SAR <?php echo number_format($order['total_amount'], 2); ?></strong></td>
                                <td>
                                    <span class="laundry-status-badge laundry-status-<?php echo $order['status'] ?: 'empty'; ?>">
                                        <?php echo ucfirst($order['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo date('M d, Y H:i', strtotime($order['created_at'])); ?></td>
                                <td>
                                    <?php if ($order['is_subscription'] == 1): ?>
                                        <span class="laundry-status-badge laundry-status-completed" style="font-size: 0.75em;">
                                            <i class="fas fa-check"></i> Auto-Activated
                                        </span>
                                    <?php else: ?>
                                        <form method="POST" style="display: inline-block;">
                                            <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                            <select name="order_status" class="laundry-status-select" required>
                                                <option value="">Change Status</option>
                                                <option value="pending" <?php echo $order['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="processing" <?php echo $order['status'] == 'processing' ? 'selected' : ''; ?>>Processing</option>
                                                <option value="ready" <?php echo $order['status'] == 'ready' ? 'selected' : ''; ?>>Ready</option>
                                            </select>
                                            <button type="submit" name="update_order_status" class="laundry-update-btn">
                                                <i class="fas fa-sync-alt"></i> Update
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="laundry-no-orders">
                    <i class="fas fa-inbox" style="font-size: 60px; color: #ddd; margin-bottom: 20px;"></i>
                    <p>No orders found</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
