<?php
require_once '../includes/User.php';
require_once '../includes/db_config.php';
if (!User::isLoggedIn()) {
    header("Location: /allura/login.php");
    exit();
}

if (!User::isAdmin()) {
    header("Location: /allura/php/profile.php");
    exit();
}

$currentUser = User::getCurrentUser();
$pdo = getDBConnection();

$today = date('Y-m-d');
$week_start = date('Y-m-d', strtotime('monday this week'));
$month_start = date('Y-m-d', strtotime('first day of this month'));
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = ?");
    $stmt->execute(array($today));
    $orders_today = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) >= ?");
    $stmt->execute(array($week_start));
    $orders_week = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) >= ?");
    $stmt->execute(array($month_start));
    $orders_month = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT SUM(total_amount) as total FROM orders WHERE status = 'completed'");
    $stmt->execute();
    $total_revenue = $stmt->fetch()['total'];
    if (!$total_revenue) $total_revenue = 0;
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = ?");
    $stmt->execute(array($today));
    $new_customers_today = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed FROM orders");
    $stmt->execute();
    $completion_stats = $stmt->fetch();
    $completion_rate = $completion_stats['total'] > 0 ? round(($completion_stats['completed'] / $completion_stats['total']) * 100, 1) : 0;
    
    $stmt = $pdo->prepare("
        SELECT o.*, 
               COALESCE(o.customer_name, u.name) as customer_name,
               GROUP_CONCAT(s.name SEPARATOR ', ') as service_names,
               GROUP_CONCAT(oi.quantity SEPARATOR ', ') as quantities,
               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();
    $active_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT user_id) as count FROM orders WHERE DATE(created_at) >= ?");
    $stmt->execute([$week_start]);
    $active_customers = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("
        SELECT u.*, 
               COUNT(o.id) as order_count,
               COALESCE(SUM(CASE WHEN o.status = 'completed' THEN o.total_amount ELSE 0 END), 0) as total_spent,
               CASE 
                   WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'Subscribed'
                   WHEN COUNT(o.id) >= 5 THEN 'Regular'
                   WHEN COUNT(o.id) > 0 THEN 'Normal'
                   ELSE 'New'
               END as customer_type,
               COALESCE(MAX(o.created_at), u.created_at) as last_activity
        FROM users u 
        LEFT JOIN orders o ON u.id = o.user_id 
        GROUP BY u.id 
        ORDER BY u.created_at DESC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("
        SELECT s.name, s.category, 
               COUNT(oi.id) as order_count,
               SUM(oi.quantity) as total_quantity,
               SUM(oi.price * oi.quantity) as total_revenue
        FROM services s
        LEFT JOIN order_items oi ON s.id = oi.service_id
        LEFT JOIN orders o ON oi.order_id = o.id AND o.status = 'completed'
        GROUP BY s.id, s.name, s.category
        ORDER BY total_revenue DESC
    ");
    $stmt->execute();
    $service_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $chart_data = [];
    $chart_labels = [];
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = ?");
        $stmt->execute([$date]);
        $count = $stmt->fetch()['count'];
        $chart_data[] = $count;
        $chart_labels[] = date('D', strtotime($date));
    }
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'new'");
    $stmt->execute();
    $new_messages = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM orders 
        WHERE status IN ('pending', 'processing') 
        AND created_at < DATE_SUB(NOW(), INTERVAL 3 DAY)
    ");
    $stmt->execute();
    $overdue_orders = $stmt->fetch()['count'];
    
    $stmt = $pdo->prepare("
        SELECT s.*, u.name as customer_name 
        FROM subscriptions s 
        LEFT JOIN users u ON s.user_id = u.id 
        WHERE s.status = 'active' 
        ORDER BY s.end_date ASC
    ");
    $stmt->execute();
    $active_subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("
        SELECT * FROM delivery_staff 
        ORDER BY status, total_deliveries DESC
    ");
    $stmt->execute();
    $delivery_staff = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("
        SELECT AVG(average_delivery_time) as avg_time 
        FROM delivery_staff 
        WHERE status != 'offline'
    ");
    $stmt->execute();
    $avg_delivery_time = $stmt->fetch()['avg_time'] ?? 0;
    
    $stmt = $pdo->prepare("
        SELECT * FROM laundry_staff 
        ORDER BY status, created_at DESC
    ");
    $stmt->execute();
    $laundry_staff = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("
        SELECT * FROM notifications 
        WHERE is_read = FALSE 
        ORDER BY created_at DESC 
        LIMIT 10
    ");
    $stmt->execute();
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("SELECT * FROM system_settings");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $settings_array = [];
    foreach ($settings as $setting) {
        $settings_array[$setting['setting_key']] = $setting['setting_value'];
    }
    
    $stmt = $pdo->prepare("
        SELECT r.*, u.name as customer_name, o.id as order_number, o.total_amount,
               ds.name as delivery_staff_name,
               GROUP_CONCAT(DISTINCT s.name SEPARATOR ', ') as services
        FROM reviews r 
        LEFT JOIN users u ON r.user_id = u.id 
        LEFT JOIN orders o ON r.order_id = o.id 
        LEFT JOIN delivery_staff ds ON o.delivery_staff_id = ds.id
        LEFT JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN services s ON oi.service_id = s.id
        GROUP BY r.id
        ORDER BY r.created_at DESC 
        LIMIT 50
    ");
    $stmt->execute();
    $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("SELECT AVG((service_rating + delivery_rating) / 2) as avg_rating, COUNT(*) as total_reviews FROM reviews");
    $stmt->execute();
    $review_stats = $stmt->fetch();
    
    $stmt = $pdo->prepare("UPDATE offers SET status = 'expired' WHERE end_date < CURDATE() AND status = 'active'");
    $stmt->execute();
    
    $stmt = $pdo->prepare("
        SELECT *, 
               CASE 
                   WHEN end_date < CURDATE() THEN 'expired'
                   WHEN start_date > CURDATE() THEN 'pending'
                   WHEN start_date <= CURDATE() AND end_date >= CURDATE() THEN 'active'
                   ELSE status
               END as computed_status
        FROM offers 
        ORDER BY 
            CASE status 
                WHEN 'active' THEN 1 
                WHEN 'inactive' THEN 2 
                WHEN 'expired' THEN 3 
                ELSE 4 
            END,
            created_at DESC
    ");
    $stmt->execute();
    $offers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as active_offers 
        FROM offers 
        WHERE status = 'active' 
        AND start_date <= CURDATE() 
        AND end_date >= CURDATE()
    ");
    $stmt->execute();
    $active_offers_count = $stmt->fetch()['active_offers'];
    
    $total_offers_count = count($offers);
    
} catch (PDOException $e) {
    $error = "Error fetching data: " . $e->getMessage();
    $orders_today = $orders_week = $orders_month = $total_revenue = $new_customers_today = $completion_rate = $active_customers = 0;
    $active_orders = $users = $service_stats = $offers = [];
    $chart_data = [0,0,0,0,0,0,0];
    $chart_labels = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
    $new_messages = $overdue_orders = $active_offers_count = $total_offers_count = 0;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard - Allura Dry Clean</title>
    <?php include '../includes/header.php'; ?>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="../css/adservices.css">
    <style>
        .location-btn {
            background: #007cba !important;
            color: white !important;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.85em;
            cursor: pointer;
            transition: background 0.3s;
        }
        .location-btn:hover {
            background: #005a8b !important;
        }
        .text-muted {
            color: #6c757d;
            font-style: italic;
            font-size: 0.9em;
        }
    </style>
    <style>
    .admin-main {
      padding: 20px;
      background: #f5f7fa;
      font-family: "Poppins", sans-serif;
    }

    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 25px;
    }

    .section-header h2 {
      font-size: 1.8rem;
      color: #333;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .stats-categories {
      display: grid;
      grid-template-columns: 1fr;
      gap: 25px;
    }

    .category-block {
      background: #fff;
      border-radius: 15px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      padding: 20px;
    }

    .category-title {
      font-weight: 600;
      font-size: 1.1rem;
      color: #555;
      margin-bottom: 15px;
      border-left: 4px solid #007bff;
      padding-left: 10px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
      gap: 15px;
    }

    .stat-card {
      background: linear-gradient(145deg, #ffffff, #f0f4f8);
      border-radius: 12px;
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 18px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    }

    .stat-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 12px rgba(0,0,0,0.1);
    }

    .stat-icon {
      font-size: 1.8rem;
      color: #007bff;
      background: #e7f0ff;
      padding: 12px;
      border-radius: 10px;
    }

    .stat-content h4 {
      font-size: 0.95rem;
      color: #555;
      margin: 0;
    }

    .stat-number {
      font-size: 1.3rem;
      font-weight: 600;
      color: #222;
      margin-top: 5px;
    }

    .chart-container {
      background: #fff;
      border-radius: 15px;
      padding: 20px;
      margin-top: 30px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }

    .chart-container h4 {
      font-size: 1.1rem;
      color: #333;
      margin-bottom: 15px;
    }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="admin-sidebar">
            <div class="sidebar-header">
                <h3><i class="fas fa-tachometer-alt"></i> Admin Panel</h3>
                <p>Welcome, <?php echo htmlspecialchars($currentUser['name']); ?></p>
            </div>

            <nav class="sidebar-nav">
                <a href="#" class="nav-item active" data-section="overview">
                    <i class="fas fa-chart-line"></i>
                    <span>Overview</span>
                </a>
                <a href="#" class="nav-item" data-section="orders">
                    <i class="fas fa-shopping-cart"></i>
                    <span>Orders</span>
                </a>
                <a href="#" class="nav-item" data-section="customers">
                    <i class="fas fa-users"></i>
                    <span>Customers</span>
                </a>
                <a href="#" class="nav-item" data-section="reviews">
                    <i class="fas fa-star"></i>
                    <span>Reviews</span>
                </a>
                <a href="#" class="nav-item" data-section="subscriptions">
                    <i class="fas fa-calendar-check"></i>
                    <span>Subscriptions</span>
                </a>
                <a href="#" class="nav-item" data-section="delivery">
                    <i class="fas fa-truck"></i>
                    <span>Delivery</span>
                </a>
                <a href="#" class="nav-item" data-section="laundry">
                    <i class="fas fa-tshirt"></i>
                    <span>Laundry Staff</span>
                </a>
                <a href="#" class="nav-item" data-section="financial">
                    <i class="fas fa-chart-pie"></i>
                    <span>Financial</span>
                </a>
                <a href="#" class="nav-item" data-section="services">
                    <i class="fas fa-box"></i>
                    <span>Services & Options</span>
                </a>
                <a href="#" class="nav-item" data-section="offers">
                    <i class="fas fa-tags"></i>
                    <span>Offers</span>
                </a>
                <a href="#" class="nav-item" data-section="notifications">
                    <i class="fas fa-bell"></i>
                    <span>Notifications</span>
                </a>
                <a href="#" class="nav-item" data-section="settings">
                    <i class="fas fa-cog"></i>
                    <span>Settings</span>
                </a>
                <a href="admin_contact.php" class="nav-item">
                    <i class="fas fa-envelope"></i>
                    <span>Contact Messages</span>
                </a>
            </nav>

            <div class="sidebar-footer">
                <a href="/php/profile.php" class="footer-btn">
                    <i class="fas fa-user"></i>
                    <span>Account</span>
                </a>
                <a href="/home.php" class="footer-btn">
                    <i class="fas fa-home"></i>
                    <span>Home</span>
                </a>
            </div>
        </div>

       <div class="admin-main">
         <?php if (isset($error)): ?>
           <div class="error-message"><?php echo htmlspecialchars($error); ?></div>
         <?php endif; ?>

         <div id="overview" class="dashboard-section active">
           <div class="section-header">
             <h2><i class="fas fa-chart-line"></i> Overview</h2>
           </div>

           <div class="stats-categories">

             <div class="category-block">
               <div class="category-title">Orders Summary</div>
               <div class="stats-grid">
                 <div class="stat-card">
                   <div class="stat-icon"><i class="fas fa-shopping-cart"></i></div>
                   <div class="stat-content">
                     <h4>Today's Orders</h4>
                     <p class="stat-number"><?php echo $orders_today; ?></p>
                   </div>
                 </div>

                 <div class="stat-card">
                   <div class="stat-icon"><i class="fas fa-calendar-week"></i></div>
                   <div class="stat-content">
                     <h4>This Week's Orders</h4>
                     <p class="stat-number"><?php echo $orders_week; ?></p>
                   </div>
                 </div>

                 <div class="stat-card">
                   <div class="stat-icon"><i class="fas fa-calendar-alt"></i></div>
                   <div class="stat-content">
                     <h4>This Month's Orders</h4>
                     <p class="stat-number"><?php echo $orders_month; ?></p>
                   </div>
                 </div>
               </div>
             </div>

             <div class="category-block">
               <div class="category-title">Performance & Revenue</div>
               <div class="stats-grid">
                 <div class="stat-card">
                   <div class="stat-icon"><i class="fas fa-dollar-sign"></i></div>
                   <div class="stat-content">
                     <h4>Total Revenue</h4>
                     <p class="stat-number">SAR <?php echo number_format($total_revenue, 2); ?></p>
                   </div>
                 </div>

                 <div class="stat-card">
                   <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                   <div class="stat-content">
                     <h4>Order Completion Rate</h4>
                     <p class="stat-number"><?php echo $completion_rate; ?>%</p>
                   </div>
                 </div>
               </div>
             </div>

             <div class="category-block">
               <div class="category-title">Customers</div>
               <div class="stats-grid">
                 <div class="stat-card">
                   <div class="stat-icon"><i class="fas fa-user-plus"></i></div>
                   <div class="stat-content">
                     <h4>New Customers Today</h4>
                     <p class="stat-number"><?php echo $new_customers_today; ?></p>
                   </div>
                 </div>
               </div>
             </div>

           </div>

           <div class="chart-container">
             <h4><i class="fas fa-chart-area"></i> Orders Trend (Last 7 Days)</h4>
             <canvas id="ordersChart"></canvas>
           </div>
         </div>
       </div>

        <div id="orders" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-shopping-cart"></i> Orders Management</h2>
            </div>
            
            <div class="orders-filters">
                <select id="orderStatusFilter" class="filter-select">
                    <option value="">All Status</option>
                    <option value="pending">Pending</option>
                    <option value="processing">Processing</option>
                    <option value="ready">Ready</option>
                    <option value="delivered">Delivered</option>
                </select>

                <select id="ordersPerPage" class="filter-select">
                    <option value="10">Show 10</option>
                    <option value="25">Show 25</option>
                    <option value="50" selected>Show 50</option>
                    <option value="100">Show 100</option>
                    <option value="all">Show All</option>
                </select>

                <div class="search-box">
                    <input type="text" id="orderSearch" placeholder="Search orders..." class="search-input">
                    <button type="button" onclick="searchOrders()" class="search-btn">
                        <i class="fas fa-search"></i> Search
                    </button>
                    <button type="button" onclick="resetOrders()" class="reset-btn">
                        <i class="fas fa-refresh"></i> Reset
                    </button>
                </div>
            </div>
            
            <div class="orders-table-container">
                <table class="orders-table">
                    <thead>
                        <tr>
                            <th>Order #</th>
                            <th>Customer Name</th>
                            <th>Services</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Location</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($active_orders as $order): ?>
                        <tr data-status="<?php echo $order['status']; ?>">
                            <td>#<?php echo $order['id']; ?></td>
                            <td><?php echo htmlspecialchars($order['customer_name'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($order['service_names'] ?? 'N/A'); ?></td>
                            <td>SAR <?php echo number_format($order['total_amount'], 2); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $order['status']; ?>">
                                    <?php 
                                    $status_text = [
                                        'pending' => 'Pending',
                                        'processing' => 'Processing',
                                        'ready' => 'Ready',
                                        'delivered' => 'Delivered',
                                        'cancelled' => 'Cancelled'
                                    ];
                                    echo $status_text[$order['status']] ?? $order['status'];
                                    ?>
                                </span>
                            </td>
                            <td>
                                <?php 
                                if (!empty($order['customer_location'])) {
                                    $location_data = json_decode($order['customer_location'], true);
                                    if ($location_data && isset($location_data['address'])) {
                                        echo '<button class="btn-small location-btn" onclick="showLocation(' . $order['id'] . ', \'' . htmlspecialchars($location_data['address']) . '\', ' . $location_data['latitude'] . ', ' . $location_data['longitude'] . ')">';
                                        echo '<i class="fas fa-map-marker-alt"></i> View';
                                        echo '</button>';
                                    } else {
                                        echo '<span class="text-muted">No location</span>';
                                    }
                                } else {
                                    echo '<span class="text-muted">No location</span>';
                                }
                                ?>
                            </td>
                            <td><?php echo date('Y-m-d 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: ?>
                                    <button class="btn-small" onclick="updateOrderStatus(<?php echo $order['id']; ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <?php if ($order['status'] !== 'delivered' && $order['status'] !== 'cancelled'): ?>
                                    <button class="btn-small btn-danger" onclick="cancelOrder(<?php echo $order['id']; ?>)" style="background: #dc3545; margin-left: 5px;">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div id="customers" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-users"></i> Customers Management</h2>
            </div>
            
            <div class="customers-stats">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Active Customers</h4>
                        <p class="stat-number"><?php echo $active_customers; ?></p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-user-plus"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Total Customers</h4>
                        <p class="stat-number"><?php echo count($users); ?></p>
                    </div>
                </div>
            </div>
            
            <table class="customers-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Type</th>
                    <th>Role</th>
                    <th>Registration Date</th>
                    <th>Orders Count</th>
                    <th>Total Spent</th>
                    <th>Last Activity</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user): ?>
                <tr>
                    <td><?php echo htmlspecialchars($user['id']); ?></td>
                    <td><?php echo htmlspecialchars($user['name']); ?></td>
                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                    <td>
                        <span class="customer-type-<?php echo $user['customer_type'] === 'Subscribed' ? 'subscribed' : ($user['customer_type'] === 'Regular' ? 'regular' : ($user['customer_type'] === 'Normal' ? 'normal' : 'new')); ?>">
                            <?php echo htmlspecialchars($user['customer_type']); ?>
                        </span>
                    </td>
                    <td>
                        <span class="role-<?php echo htmlspecialchars($user['role']); ?>">
                            <?php echo ucfirst(htmlspecialchars($user['role'])); ?>
                        </span>
                    </td>
                    <td><?php echo date('Y-m-d', strtotime($user['created_at'])); ?></td>
                    <td><?php echo $user['order_count']; ?></td>
                    <td>SAR <?php echo number_format($user['total_spent'], 2); ?></td>
                    <td><?php echo date('Y-m-d', strtotime($user['last_activity'])); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            </table>
        </div>
        
        <div id="reviews" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-star"></i> Customer Reviews</h2>
            </div>
            
            <div class="reviews-stats">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-star"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Average Rating</h4>
                        <p class="stat-number"><?php echo number_format($review_stats['avg_rating'] ?? 0, 1); ?>/5</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-comments"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Total Reviews</h4>
                        <p class="stat-number"><?php echo $review_stats['total_reviews'] ?? 0; ?></p>
                    </div>
                </div>
            </div>
            
            <?php if (!empty($reviews)): ?>
            <div class="reviews-list">
                <?php foreach ($reviews as $review): ?>
                <div class="review-item">
                    <div class="review-header">
                        <div class="customer-info">
                            <h4><?php echo htmlspecialchars($review['customer_name'] ?? 'Unknown Customer'); ?></h4>
                            <span class="order-info">Order #<?php echo $review['order_number']; ?> - $<?php echo number_format($review['total_amount'], 2); ?></span>
                        </div>
                        <div class="review-rating">
                            <?php 
                            $avg_rating = round(($review['service_rating'] + $review['delivery_rating']) / 2);
                            for ($i = 1; $i <= 5; $i++): ?>
                                <i class="<?php echo $i <= $avg_rating ? 'fas' : 'far'; ?> fa-star"></i>
                            <?php endfor; ?>
                            <span class="rating-text"><?php echo $avg_rating; ?>/5</span>
                            <small>(Service: <?php echo $review['service_rating']; ?>, Delivery: <?php echo $review['delivery_rating']; ?>)</small>
                        </div>
                    </div>
                    <div class="review-content">
                        <p><?php echo htmlspecialchars($review['comment'] ?? 'No comment provided'); ?></p>
                        
                        <!-- Service and Staff Details -->
                        <div class="review-details">
                            <?php if (!empty($review['services'])): ?>
                            <div class="detail-item">
                                <i class="fas fa-tshirt"></i>
                                <span><strong>Services:</strong> <?php echo htmlspecialchars($review['services']); ?></span>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($review['delivery_staff_name'])): ?>
                            <div class="detail-item">
                                <i class="fas fa-user-tie"></i>
                                <span><strong>Delivery Staff:</strong> <?php echo htmlspecialchars($review['delivery_staff_name']); ?></span>
                            </div>
                            <?php endif; ?>
                            
                            <div class="detail-item">
                                <i class="fas fa-user"></i>
                                <span><strong>Customer:</strong> <?php echo htmlspecialchars($review['customer_name'] ?? 'Unknown Customer'); ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="review-footer">
                        <span class="review-date">
                            <i class="fas fa-calendar-alt"></i>
                            <?php echo date('Y-m-d H:i', strtotime($review['created_at'])); ?>
                        </span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div class="no-data">
                <i class="fas fa-star-half-alt"></i>
                <p>No reviews available</p>
            </div>
            <?php endif; ?>
        </div>
        
        <div id="subscriptions" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-calendar-check"></i> Subscriptions Management</h2>
            </div>
            
            <?php 
            $stmt = $pdo->prepare("
                SELECT s.*, u.name as customer_name, u.email as customer_email,
                       DATEDIFF(s.end_date, CURDATE()) as days_left
                FROM subscriptions s 
                LEFT JOIN users u ON s.user_id = u.id 
                WHERE s.status = 'active' 
                AND s.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
                ORDER BY s.end_date ASC
            ");
            $stmt->execute();
            $expiring_subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM subscriptions");
            $stmt->execute();
            $total_subs = $stmt->fetch()['total'];
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as active FROM subscriptions WHERE status = 'active'");
            $stmt->execute();
            $active_subs_count = $stmt->fetch()['active'];
            
            $stmt = $pdo->prepare("SELECT COUNT(*) as expired FROM subscriptions WHERE status = 'expired' OR end_date < CURDATE()");
            $stmt->execute();
            $expired_subs = $stmt->fetch()['expired'];
            
            $stmt = $pdo->prepare("SELECT SUM(price) as revenue FROM subscriptions WHERE status = 'active'");
            $stmt->execute();
            $monthly_revenue = $stmt->fetch()['revenue'] ?? 0;
            ?>
            
            <?php if (!empty($expiring_subscriptions)): ?>
            <div class="alert alert-warning" style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                <h4 style="margin: 0 0 10px 0; color: #856404;"><i class="fas fa-exclamation-triangle"></i> Expiring Subscriptions Alert</h4>
                <div class="expiring-subs-list">
                    <?php foreach ($expiring_subscriptions as $sub): ?>
                    <div class="expiring-sub-item" style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #ffeaa7;">
                        <div>
                            <strong><?php echo htmlspecialchars($sub['customer_name']); ?></strong> - <?php echo htmlspecialchars($sub['plan_name']); ?>
                            <br><small><?php echo htmlspecialchars($sub['customer_email']); ?></small>
                        </div>
                        <div style="text-align: right;">
                            <span class="days-left" style="color: <?php echo $sub['days_left'] <= 1 ? '#dc3545' : '#856404'; ?>; font-weight: bold;">
                                <?php echo $sub['days_left']; ?> day(s) left
                            </span>
                            <br><small>Expires: <?php echo date('Y-m-d', strtotime($sub['end_date'])); ?></small>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="subscriptions-management">
                <div class="management-tabs">
                    <button class="tab-btn active" onclick="showSubscriptionTab('subscriptions-list')">
                        <i class="fas fa-list"></i> All Subscriptions
                    </button>
                    <button class="tab-btn" onclick="showSubscriptionTab('subscription-plans')">
                        <i class="fas fa-tags"></i> Subscription Plans
                    </button>
                    <button class="tab-btn" onclick="showSubscriptionTab('subscription-stats')">
                        <i class="fas fa-chart-bar"></i> Statistics
                    </button>
                </div>
                
                <!-- Subscriptions List Tab -->
                <div id="subscriptions-list" class="management-content active">
                    <div class="content-header">
                        <h3>All Subscriptions</h3>
                        <div style="display: flex; gap: 10px;">
                            <select id="subscriptionStatusFilter" onchange="filterSubscriptions()" class="filter-select">
                                <option value="">All Status</option>
                                <option value="active">Active</option>
                                <option value="expired">Expired</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                            <button class="btn btn-primary" onclick="openSubscriptionForm()">
                                <i class="fas fa-plus"></i> Add New Subscription
                            </button>
                        </div>
                    </div>
                    
                    <div class="subscriptions-table-container">
                        <table class="subscriptions-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Customer</th>
                                    <th>Plan</th>
                                    <th>Price</th>
                                    <th>Start Date</th>
                                    <th>End Date</th>
                                    <th>Usage</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="subscriptionsTableBody">
                                <tr><td colspan="9" class="loading-state">Loading subscriptions...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div id="subscription-plans" class="management-content">
                    <div class="content-header">
                        <h3>Available Subscription Plans (Templates)</h3>
                    </div>
                    
                    <div class="plans-grid" id="plansGrid">
                        <div class="loading-state">Loading plans...</div>
                    </div>
                </div>
                
                <div id="subscription-stats" class="management-content">
                    <div class="content-header">
                        <h3>Subscription Statistics</h3>
                    </div>
                    
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-icon">
                                <i class="fas fa-list"></i>
                            </div>
                            <div class="stat-content">
                                <h4>Total Subscriptions</h4>
                                <p class="stat-number"><?php echo $total_subs; ?></p>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-icon">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="stat-content">
                                <h4>Active Subscriptions</h4>
                                <p class="stat-number"><?php echo $active_subs_count; ?></p>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-icon">
                                <i class="fas fa-times-circle"></i>
                            </div>
                            <div class="stat-content">
                                <h4>Expired Subscriptions</h4>
                                <p class="stat-number"><?php echo $expired_subs; ?></p>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-icon">
                                <i class="fas fa-dollar-sign"></i>
                            </div>
                            <div class="stat-content">
                                <h4>Monthly Revenue</h4>
                                <p class="stat-number">SAR <?php echo number_format($monthly_revenue, 2); ?></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="stats-details" style="margin-top: 30px;">
                        <h4>Recent Activity</h4>
                        <div id="recentActivity">
                            <div class="loading-state">Loading activity...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="delivery" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-truck"></i> Delivery Management</h2>
            </div>
            <div class="delivery-stats">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-truck"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Available Staff</h4>
                        <p class="stat-number"><?php echo count(array_filter($delivery_staff, function($staff) { return $staff['status'] == 'available'; })); ?></p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Average Delivery Time</h4>
                        <p class="stat-number"><?php echo round($avg_delivery_time); ?> min</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Total Staff</h4>
                        <p class="stat-number"><?php echo count($delivery_staff); ?></p>
                    </div>
                </div>
            </div>
            
            <?php if (!empty($delivery_staff)): ?>
            <table class="delivery-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Deliveries</th>
                        <th>Avg Time</th>
                        <th>Rating</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($delivery_staff as $staff): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($staff['name']); ?></td>
                        <td><?php echo htmlspecialchars($staff['phone']); ?></td>
                        <td>
                            <span class="status-badge status-<?php echo $staff['status']; ?>">
                                <?php 
                                $status_text = [
                                    'available' => 'Available',
                                    'busy' => 'Busy',
                                    'offline' => 'Offline'
                                ];
                                echo $status_text[$staff['status']] ?? $staff['status'];
                                ?>
                            </span>
                        </td>
                        <td><?php echo $staff['total_deliveries']; ?></td>
                        <td><?php echo $staff['average_delivery_time']; ?> min</td>
                        <td>
                            <div class="rating">
                                <?php 
                                $rating = round($staff['rating']);
                                for ($i = 1; $i <= 5; $i++): 
                                ?>
                                    <i class="<?php echo $i <= $rating ? 'fas' : 'far'; ?> fa-star"></i>
                                <?php endfor; ?>
                            </div>
                        </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
            <?php else: ?>
            <div class="no-data">
                <i class="fas fa-truck"></i>
                <p>No delivery staff registered</p>
            </div>
            <?php endif; ?>
        </div>
        
        <div id="laundry" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-tshirt"></i> Laundry Staff Management</h2>
                <button class="btn-primary" onclick="showAddLaundryStaffModal()">
                    <i class="fas fa-plus"></i> Add New Staff
                </button>
            </div>
            
            <div class="delivery-stats">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Total Staff</h4>
                        <p class="stat-number"><?php echo count($laundry_staff); ?></p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Active Staff</h4>
                        <p class="stat-number"><?php echo count(array_filter($laundry_staff, function($staff) { return $staff['status'] == 'active'; })); ?></p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-user-times"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Inactive Staff</h4>
                        <p class="stat-number"><?php echo count(array_filter($laundry_staff, function($staff) { return $staff['status'] == 'inactive'; })); ?></p>
                    </div>
                </div>
            </div>
            
            <?php if (!empty($laundry_staff)): ?>
            <table class="delivery-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Last Login</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($laundry_staff as $staff): ?>
                    <tr>
                        <td>#<?php echo $staff['id']; ?></td>
                        <td><?php echo htmlspecialchars($staff['name']); ?></td>
                        <td><?php echo htmlspecialchars($staff['email']); ?></td>
                        <td><?php echo htmlspecialchars($staff['phone']); ?></td>
                        <td>
                            <span class="status-badge status-<?php echo $staff['status']; ?>">
                                <?php echo ucfirst($staff['status']); ?>
                            </span>
                        </td>
                        <td><?php echo $staff['last_login'] ? date('M d, Y H:i', strtotime($staff['last_login'])) : 'Never'; ?></td>
                        <td>
                            <div class="laundry-staff-actions">
                                <button class="btn-small btn-edit" onclick="editLaundryStaff(<?php echo htmlspecialchars(json_encode($staff)); ?>)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn-small btn-delete" onclick="deleteLaundryStaff(<?php echo $staff['id']; ?>, '<?php echo htmlspecialchars($staff['name']); ?>')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="no-data">
                <i class="fas fa-tshirt"></i>
                <p>No laundry staff registered</p>
            </div>
            <?php endif; ?>
        </div>
        
        <div id="financial" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-chart-pie"></i> Financial Reports</h2>
            </div>
            
            <?php
            $stmt = $pdo->prepare("SELECT SUM(total_amount) as total_revenue FROM orders WHERE status = 'completed'");
            $stmt->execute();
            $total_revenue = $stmt->fetch()['total_revenue'] ?? 0;
            
            $stmt = $pdo->prepare("SELECT SUM(price) as subscription_revenue FROM subscriptions WHERE status = 'active'");
            $stmt->execute();
            $subscription_revenue = $stmt->fetch()['subscription_revenue'] ?? 0;
            
            $stmt = $pdo->prepare("SELECT SUM(amount) as total_expenses FROM expenses WHERE expense_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
            $stmt->execute();
            $total_expenses = $stmt->fetch()['total_expenses'] ?? 0;
            
            $net_profit = $total_revenue - $total_expenses;
            
            $stmt = $pdo->prepare("
                SELECT category, SUM(amount) as total_amount, COUNT(*) as count
                FROM expenses 
                WHERE expense_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                GROUP BY category 
                ORDER BY total_amount DESC
            ");
            $stmt->execute();
            $expense_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
            ?>
            
            <div class="financial-overview">
                <div class="financial-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="stat-content">
                            <h4>Total Revenue</h4>
                            <p class="stat-number">SAR <?php echo number_format($total_revenue, 2); ?></p>
                            <small>From completed orders</small>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-calendar-check"></i>
                        </div>
                        <div class="stat-content">
                            <h4>Subscription Revenue</h4>
                            <p class="stat-number">SAR <?php echo number_format($subscription_revenue, 2); ?></p>
                            <small>Active subscriptions</small>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-minus-circle"></i>
                        </div>
                        <div class="stat-content">
                            <h4>Total Expenses (30 days)</h4>
                            <p class="stat-number">SAR <?php echo number_format($total_expenses, 2); ?></p>
                            <small>Operating costs</small>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas <?php echo $net_profit >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'; ?>"></i>
                        </div>
                        <div class="stat-content">
                            <h4>Net Profit</h4>
                            <p class="stat-number" style="color: <?php echo $net_profit >= 0 ? '#28a745' : '#dc3545'; ?>;">
                                SAR <?php echo number_format($net_profit, 2); ?>
                            </p>
                            <small>Revenue - Expenses</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Revenue by Service Section -->
            <div class="financial-section">
                <div class="services-revenue">
                    <h4>Revenue by Service</h4>
                    <div class="services-grid">
                        <?php foreach ($service_stats as $service): ?>
                        <div class="service-revenue-item">
                            <div class="service-info">
                                <h5><?php echo htmlspecialchars($service['name']); ?></h5>
                                <p>SAR <?php echo number_format($service['total_revenue'] ?? 0, 2); ?></p>
                            </div>
                            <div class="service-details">
                                <small><?php echo $service['order_count']; ?> orders</small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            
            <!-- Expenses Section -->
            <div class="financial-section">
                <div class="expenses-breakdown">
                    <h4>Expenses Breakdown (Last 30 Days)</h4>
                    <?php if (!empty($expense_categories)): ?>
                    <div class="expenses-grid">
                        <?php foreach ($expense_categories as $category): ?>
                        <div class="expense-item">
                            <div class="expense-info">
                                <h5><?php echo ucfirst($category['category']); ?></h5>
                                <p>SAR <?php echo number_format($category['total_amount'], 2); ?></p>
                            </div>
                            <div class="expense-details">
                                <small><?php echo $category['count']; ?> transactions</small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="no-data">
                        <i class="fas fa-receipt"></i>
                        <p>No expenses recorded in the last 30 days.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div id="services" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-box"></i> Services & Options Management</h2>
            </div>
            
            <div class="services-management">
                <div class="management-tabs">
                    <button class="tab-btn active" onclick="showManagementTab('services-list')">
                        <i class="fas fa-list"></i> Services
                    </button>
                    <button class="tab-btn" onclick="showManagementTab('options-list')">
                        <i class="fas fa-sliders-h"></i> Service Options
                    </button>
                </div>
                
                <div id="services-list" class="management-content active">
                    <div class="content-header">
                        <h3>All Services</h3>
                        <button class="btn btn-primary" onclick="openServiceForm()">
                            <i class="fas fa-plus"></i> Add New Service
                        </button>
                    </div>
                    
                    <div class="services-grid" id="servicesGrid">
                        <div class="loading-state">Loading services...</div>
                    </div>
                </div>
                
                <div id="options-list" class="management-content">
                    <div class="content-header">
                        <h3>Service Options</h3>
                        <div class="filter-group">
                            <label>Filter by Service:</label>
                            <select id="serviceFilter" onchange="loadOptions()">
                                <option value="">All Services</option>
                            </select>
                            <button class="btn btn-primary" onclick="openOptionForm()">
                                <i class="fas fa-plus"></i> Add Option
                            </button>
                        </div>
                    </div>
                    
                    <div class="options-table-container">
                        <table class="options-table" id="optionsTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Service</th>
                                    <th>Type</th>
                                    <th>Name</th>
                                    <th>Value</th>
                                    <th>Price Modifier</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="optionsTableBody">
                                <tr><td colspan="7" class="loading-state">Loading options...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div id="offers" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-tags"></i> Offers & Discounts Management</h2>
            </div>
            
            <div class="offers-stats">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-tags"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Active Offers</h4>
                        <p class="stat-number"><?php echo $active_offers_count; ?></p>
                        <small>Currently available</small>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-percentage"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Total Offers</h4>
                        <p class="stat-number"><?php echo $total_offers_count ?? count($offers); ?></p>
                        <small>All offers in system</small>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-pause-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Inactive Offers</h4>
                        <p class="stat-number"><?php 
                            $inactive_count = 0;
                            foreach($offers as $offer) {
                                if($offer['status'] == 'inactive') $inactive_count++;
                            }
                            echo $inactive_count;
                        ?></p>
                        <small>Paused offers</small>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <h4>Expired Offers</h4>
                        <p class="stat-number"><?php 
                            $expired_count = 0;
                            foreach($offers as $offer) {
                                if($offer['status'] == 'expired' || strtotime($offer['end_date']) < time()) $expired_count++;
                            }
                            echo $expired_count;
                        ?></p>
                        <small>Past offers</small>
                    </div>
                </div>
            </div>
            
            <div class="offers-actions" style="margin: 20px 0;">
                <button class="btn btn-primary" onclick="showAddOfferForm()">
                    <i class="fas fa-plus"></i> Add New Offer
                </button>
            </div>
            
            <?php if (!empty($offers)): ?>
            <div class="offers-list">
                <?php foreach ($offers as $offer): ?>
                <div class="offer-item">
                    <div class="offer-header">
                        <div class="offer-info">
                            <h4><?php echo htmlspecialchars($offer['title']); ?></h4>
                            <p><?php echo htmlspecialchars($offer['description']); ?></p>
                        </div>
                        <div class="offer-status">
                            <span class="status-badge status-<?php echo $offer['status']; ?>">
                                <?php echo ucfirst($offer['status']); ?>
                            </span>
                        </div>
                    </div>
                    <div class="offer-details">
                        <div class="offer-discount">
                            <strong>Discount:</strong>
                            <?php if ($offer['discount_type'] === 'percentage'): ?>
                                <?php echo $offer['discount_value']; ?>% off
                            <?php else: ?>
                                $<?php echo number_format($offer['discount_value'], 2); ?> off
                            <?php endif; ?>
                        </div>
                        <div class="offer-conditions">
                            <?php if ($offer['min_order_amount'] > 0): ?>
                                <span>Min. order: $<?php echo number_format($offer['min_order_amount'], 2); ?></span>
                            <?php endif; ?>
                            <?php if ($offer['max_discount_amount']): ?>
                                <span>Max. discount: $<?php echo number_format($offer['max_discount_amount'], 2); ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="offer-period">
                            <span>Valid: <?php echo date('Y-m-d', strtotime($offer['start_date'])); ?> to <?php echo date('Y-m-d', strtotime($offer['end_date'])); ?></span>
                        </div>
                        <div class="offer-target">
                            <span>Target: <?php echo ucfirst($offer['target_customers']); ?> customers</span>
                        </div>
                        <?php if ($offer['usage_limit']): ?>
                        <div class="offer-usage">
                            <span>Usage: <?php echo $offer['used_count']; ?> / <?php echo $offer['usage_limit']; ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="offer-actions">
                        <button class="btn-small" onclick="editOffer(<?php echo $offer['id']; ?>)">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <button class="btn-small btn-danger" onclick="deleteOffer(<?php echo $offer['id']; ?>)">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                        <?php if ($offer['status'] === 'active' && strtotime($offer['start_date']) <= time() && strtotime($offer['end_date']) >= time()): ?>
                        <button class="btn-small btn-info" onclick="sendSingleOffer(<?php echo $offer['id']; ?>, '<?php echo htmlspecialchars($offer['title']); ?>', '<?php echo $offer['target_customers']; ?>')">
                            <i class="fas fa-paper-plane"></i> Send
                        </button>
                        <?php endif; ?>
                        <?php if ($offer['status'] === 'active'): ?>
                        <button class="btn-small btn-warning" onclick="toggleOfferStatus(<?php echo $offer['id']; ?>, 'inactive')">
                            <i class="fas fa-pause"></i> Deactivate
                        </button>
                        <?php else: ?>
                        <button class="btn-small btn-success" onclick="toggleOfferStatus(<?php echo $offer['id']; ?>, 'active')">
                            <i class="fas fa-play"></i> Activate
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div class="no-data">
                <i class="fas fa-tags"></i>
                <p>No offers available</p>
            </div>
            <?php endif; ?>
        </div>
        
        <div id="notifications" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-bell"></i> Notifications</h2>
            </div>
            <div class="notifications-list">
                <?php if (!empty($notifications)): ?>
                    <?php foreach ($notifications as $notification): ?>
                    <div class="notification-item <?php echo $notification['type']; ?>">
                        <i class="fas fa-<?php echo $notification['type'] == 'warning' ? 'exclamation-triangle' : ($notification['type'] == 'success' ? 'check-circle' : ($notification['type'] == 'error' ? 'times-circle' : 'info-circle')); ?>"></i>
                        <div class="notification-content">
                            <h4><?php echo htmlspecialchars($notification['title']); ?></h4>
                            <p><?php echo htmlspecialchars($notification['message']); ?></p>
                            <span class="notification-time"><?php echo date('Y-m-d H:i', strtotime($notification['created_at'])); ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <?php if ($overdue_orders > 0): ?>
                    <div class="notification-item warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        <div class="notification-content">
                            <h4>Overdue Orders</h4>
                            <p>There are <?php echo $overdue_orders; ?> overdue orders</p>
                            <span class="notification-time">Now</span>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php 
                    $stmt = $pdo->prepare("
                        SELECT COUNT(*) as count 
                        FROM subscriptions s 
                        LEFT JOIN users u ON s.user_id = u.id 
                        WHERE s.status = 'active' 
                        AND s.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
                    ");
                    $stmt->execute();
                    $expiring_subs = $stmt->fetch()['count'];
                    
                    if ($expiring_subs > 0): ?>
                    <div class="notification-item warning">
                        <i class="fas fa-calendar-times"></i>
                        <div class="notification-content">
                            <h4>Expiring Subscriptions</h4>
                            <p><?php echo $expiring_subs; ?> subscription(s) will expire within 3 days</p>
                            <span class="notification-time">Now</span>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($new_messages > 0): ?>
                    <div class="notification-item info">
                        <i class="fas fa-envelope"></i>
                        <div class="notification-content">
                            <h4>New Messages</h4>
                            <p>There are <?php echo $new_messages; ?> new messages from customers</p>
                            <span class="notification-time">Now</span>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($new_customers_today > 0): ?>
                    <div class="notification-item success">
                        <i class="fas fa-user-plus"></i>
                        <div class="notification-content">
                            <h4>New Customers</h4>
                            <p><?php echo $new_customers_today; ?> new customers registered today</p>
                            <span class="notification-time">Today</span>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($orders_today > 0): ?>
                    <div class="notification-item info">
                        <i class="fas fa-shopping-cart"></i>
                        <div class="notification-content">
                            <h4>New Orders</h4>
                            <p><?php echo $orders_today; ?> new orders received today</p>
                            <span class="notification-time">Today</span>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (empty($overdue_orders) && empty($new_messages) && empty($new_customers_today) && empty($orders_today)): ?>
                    <div class="no-data">
                        <i class="fas fa-bell-slash"></i>
                        <p>No notifications available</p>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <div id="settings" class="dashboard-section">
            <div class="section-header">
                <h2><i class="fas fa-cog"></i> System Settings</h2>
            </div>
            <div class="settings-grid">
                <div class="setting-card">
                    <h4><i class="fas fa-tags"></i> Pricing Management</h4>
                    <p>Manage service prices</p>
                    <div class="setting-value">
                        <strong>Delivery Fee:</strong> $<span id="delivery_fee_value"><?php echo $settings_array['delivery_fee'] ?? 'Not set'; ?></span><br>
                        <strong>Minimum Order:</strong> $<span id="min_order_value"><?php echo $settings_array['min_order_amount'] ?? 'Not set'; ?></span>
                    </div>
                    <button class="btn" onclick="editPricing()">Edit</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-users-cog"></i> Staff Management</h4>
                    <p>Add or remove staff members</p>
                    <div class="setting-value">
                        <strong>Total Staff:</strong> <span id="total_staff_count"><?php echo count($delivery_staff); ?></span><br>
                        <strong>Available:</strong> <span id="available_staff_count"><?php echo count(array_filter($delivery_staff, function($staff) { return $staff['status'] == 'available'; })); ?></span>
                    </div>
                    <button class="btn" onclick="manageStaff()">Manage</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-clock"></i> Working Hours</h4>
                    <p>Set working hours and holidays</p>
                    <div class="setting-value">
                        <strong>From:</strong> <span id="work_start_value"><?php echo $settings_array['working_hours_start'] ?? 'Not set'; ?></span><br>
                        <strong>To:</strong> <span id="work_end_value"><?php echo $settings_array['working_hours_end'] ?? 'Not set'; ?></span>
                    </div>
                    <button class="btn" onclick="editWorkingHours()">Edit</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-truck"></i> Delivery Settings</h4>
                    <p>Configure delivery settings</p>
                    <div class="setting-value">
                        <strong>Max Delivery Time:</strong> <span id="max_delivery_value"><?php echo $settings_array['max_delivery_time'] ?? 'Not set'; ?></span> minutes
                    </div>
                    <button class="btn" onclick="editDeliverySettings()">Edit</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-envelope"></i> Contact Information</h4>
                    <p>Update company information</p>
                    <div class="setting-value">
                        <strong>Phone:</strong> <span id="company_phone_value"><?php echo $settings_array['company_phone'] ?? 'Not set'; ?></span><br>
                        <strong>Email:</strong> <span id="company_email_value"><?php echo $settings_array['notification_email'] ?? 'Not set'; ?></span>
                    </div>
                    <button class="btn" onclick="editContactInfo()">Edit</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-map-marker-alt"></i> Company Address</h4>
                    <p>Update company address</p>
                    <div class="setting-value">
                        <span id="company_address_value"><?php echo $settings_array['company_address'] ?? 'Not set'; ?></span>
                    </div>
                    <button class="btn" onclick="editCompanyAddress()">Edit</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-box"></i> Services Management</h4>
                    <p>Manage services, prices and images</p>
                    <div class="setting-value">
                        <strong>Total Services:</strong> <span id="total_services_count"><?php 
                            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM services");
                            $stmt->execute();
                            echo $stmt->fetch()['count'];
                        ?></span>
                    </div>
                    <button class="btn" onclick="manageServices()">Manage</button>
                </div>
                
                <div class="setting-card">
                    <h4><i class="fas fa-receipt"></i> Expenses Management</h4>
                    <p>Track and manage business expenses</p>
                    <div class="setting-value">
                        <strong>This Month:</strong> <span id="monthly_expenses">SAR <?php 
                            $stmt = $pdo->prepare("SELECT SUM(amount) as total FROM expenses WHERE MONTH(expense_date) = MONTH(CURDATE()) AND YEAR(expense_date) = YEAR(CURDATE())");
                            $stmt->execute();
                            echo number_format($stmt->fetch()['total'] ?? 0, 2);
                        ?></span>
                    </div>
                    <button class="btn" onclick="manageExpenses()">Manage</button>
                </div>
            </div>
        </div>
    </div>

    <div id="settingsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Settings</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="settingsForm">
                    <div id="modalFields">
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div id="orderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Edit Order</h3>
                <span class="close" onclick="closeOrderModal()">&times;</span>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                <form id="orderForm">
                    <div class="form-group">
                        <label>Order ID</label>
                        <input type="text" id="order_id_display" readonly>
                        <input type="hidden" id="order_id" name="order_id">
                    </div>
                    <div class="form-group">
                        <label>Customer Name</label>
                        <input type="text" id="customer_name_display" readonly>
                    </div>
                    <div class="form-group">
                        <label>Services</label>
                        <input type="text" id="services_display" readonly>
                    </div>
                    <div class="form-group">
                        <label>Total Amount</label>
                        <input type="text" id="total_amount_display" readonly>
                    </div>
                    <div class="form-group">
                        <label for="order_status">Status <span style="color: red;">*</span></label>
                        <select id="order_status" name="status" required>
                            <option value="pending">Pending</option>
                            <option value="processing">Processing</option>
                            <option value="ready">Ready</option>
                            <option value="delivered">Delivered</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeOrderModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Order</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div id="staffModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Staff Management</h3>
                <span class="close" onclick="closeStaffModal()">&times;</span>
            </div>
            <div class="modal-body" style="max-height: 60vh; overflow-y: auto;">
                <div class="staff-actions" style="margin-bottom: 20px; display: flex; gap: 10px;">
                    <button class="btn btn-primary" onclick="showAddStaffForm()" style="display: flex; align-items: center; gap: 5px;">
                        <i class="fas fa-plus"></i> Add New Staff
                    </button>
                    <button class="btn btn-secondary" onclick="showStaffList()" style="display: flex; align-items: center; gap: 5px;">
                        <i class="fas fa-list"></i> View Staff List
                    </button>
                </div>
                <div id="staffContent">
                </div>
                <div class="modal-actions" style="margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px;">
                </div>
            </div>
        </div>
    </div>

    <div id="servicesModal" class="modal">
        <div class="modal-content" style="max-width: 900px;">
            <div class="modal-header">
                <h3>Services Management</h3>
                <span class="close" onclick="closeServicesModal()">&times;</span>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                <div class="services-actions" style="margin-bottom: 20px; display: flex; gap: 10px;">
                    <button class="btn btn-primary" onclick="showAddServiceForm()" style="display: flex; align-items: center; gap: 5px;">
                        <i class="fas fa-plus"></i> Add New Service
                    </button>
                    <button class="btn btn-secondary" onclick="showServicesList()" style="display: flex; align-items: center; gap: 5px;">
                        <i class="fas fa-list"></i> View Services List
                    </button>
                </div>
                <div id="servicesContent">
                </div>
            </div>
        </div>
    </div>

    <div id="expensesModal" class="modal">
        <div class="modal-content" style="max-width: 900px;">
            <div class="modal-header">
                <h3>Expenses Management</h3>
                <span class="close" onclick="closeExpensesModal()">&times;</span>
            </div>
            <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                <div class="expenses-actions" style="margin-bottom: 20px; display: flex; gap: 10px;">
                    <button class="btn btn-primary" onclick="showAddExpenseForm()" style="display: flex; align-items: center; gap: 5px;">
                        <i class="fas fa-plus"></i> Add New Expense
                    </button>
                    <button class="btn btn-secondary" onclick="showExpensesList()" style="display: flex; align-items: center; gap: 5px;">
                        <i class="fas fa-list"></i> View Expenses List
                    </button>
                </div>
                <div id="expensesContent">
                </div>
            </div>
        </div>
    </div>

    <div id="serviceModal" class="modal">
        <div class="modal-content" style="max-width: 700px;">
            <div class="modal-header">
                <h3 id="serviceModalTitle">Add New Service</h3>
                <span class="close" onclick="closeServiceModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="serviceForm">
                    <input type="hidden" id="service_id" name="id">
                    <input type="hidden" name="action" value="save_service">
                    
                    <div class="form-group">
                        <label>Service Name *</label>
                        <input type="text" name="name" id="service_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Description *</label>
                        <textarea name="description" id="service_description" rows="4" required></textarea>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Price (SAR) *</label>
                            <input type="number" name="price" id="service_price" step="0.01" min="0" required>
                        </div>
                        
                        <div class="form-group">
                            <label>Category *</label>
                            <select name="category" id="service_category" required>
                                <option value="complete_washing">Complete Washing</option>
                                <option value="ironing">Ironing</option>
                                <option value="carpet">Carpet & Curtain</option>
                                <option value="shoes">Shoes</option>
                                <option value="household">Household Items</option>
                                <option value="subscription">Subscription</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Image URL</label>
                        <input type="text" name="image" id="service_image" placeholder="img/service.jpg">
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeServiceModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Service</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div id="optionModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 id="optionModalTitle">Add New Option</h3>
                <span class="close" onclick="closeOptionModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="optionForm">
                    <input type="hidden" id="option_id" name="id">
                    <input type="hidden" name="action" value="save_option">
                    
                    <div class="form-group">
                        <label>Service *</label>
                        <select name="service_id" id="option_service_id" required>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Option Type *</label>
                        <select name="option_type" id="option_type" required>
                            <option value="fabric_type">Fabric Type</option>
                            <option value="gender">Gender</option>
                            <option value="detergent">Detergent</option>
                            <option value="delivery_time">Delivery Time</option>
                            <option value="ironing_type">Ironing Type</option>
                            <option value="cleaning_method">Cleaning Method</option>
                            <option value="temperature">Temperature</option>
                            <option value="optional_ironing">Optional Ironing</option>
                            <option value="service_type">Service Type</option>
                            <option value="item_type">Item Type</option>
                            <option value="garment_size">Garment Size</option>
                            <option value="cleaning_preference">Cleaning Preference</option>
                            <option value="optional_addon">Optional Addon</option>
                            <option value="delivery_speed">Delivery Speed</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Option Name *</label>
                        <input type="text" name="option_name" id="option_name" required placeholder="e.g., Cotton, Men, Express">
                    </div>
                    
                    <div class="form-group">
                        <label>Option Value *</label>
                        <input type="text" name="option_value" id="option_value" required placeholder="e.g., cotton, men, express">
                        <small>Use lowercase, no spaces (use underscore)</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Price Modifier (SAR)</label>
                        <input type="number" name="price_modifier" id="option_price_modifier" step="0.01" value="0.00">
                        <small>Additional price (use negative for discounts)</small>
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeOptionModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Option</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Subscription Modal -->
    <div id="subscriptionModal" class="modal">
        <div class="modal-content" style="max-width: 700px;">
            <div class="modal-header">
                <h3 id="subscriptionModalTitle">Add New Subscription</h3>
                <span class="close" onclick="closeSubscriptionModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="subscriptionForm">
                    <input type="hidden" id="subscription_id" name="id">
                    <input type="hidden" name="action" value="save_subscription">
                    
                    <div class="form-group">
                        <label>Customer *</label>
                        <select name="user_id" id="subscription_user_id" required>
                            <option value="">Select Customer</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Plan Name *</label>
                        <input type="text" name="plan_name" id="subscription_plan_name" required placeholder="e.g., Monthly Basic">
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Price (SAR) *</label>
                            <input type="number" name="price" id="subscription_price" step="0.01" min="0" required>
                        </div>
                        
                        <div class="form-group">
                            <label>Max Usage *</label>
                            <input type="number" name="max_usage" id="subscription_max_usage" min="1" required placeholder="Number of uses">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Start Date *</label>
                            <input type="date" name="start_date" id="subscription_start_date" required>
                        </div>
                        
                        <div class="form-group">
                            <label>End Date *</label>
                            <input type="date" name="end_date" id="subscription_end_date" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Status *</label>
                        <select name="status" id="subscription_status" required>
                            <option value="active">Active</option>
                            <option value="expired">Expired</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeSubscriptionModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Subscription</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Plan Edit Modal -->
    <div id="planModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 id="planModalTitle">Edit Subscription Plan</h3>
                <span class="close" onclick="closePlanModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="planForm">
                    <input type="hidden" id="plan_id" name="id">
                    <input type="hidden" name="action" value="save_plan">
                    
                    <div class="form-group">
                        <label>Plan Type</label>
                        <input type="text" id="plan_type_display" readonly style="background: #f5f5f5;">
                    </div>
                    
                    <div class="form-group">
                        <label>Plan Name *</label>
                        <input type="text" name="plan_name" id="plan_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Base Price (SAR)</label>
                        <input type="number" id="plan_base_price" step="0.01" readonly style="background: #f5f5f5;">
                        <small>Base price from services table (read-only)</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Price Modifier (SAR) *</label>
                        <input type="number" name="price_modifier" id="plan_price_modifier" step="0.01" required>
                        <small>Additional amount added to base price (can be positive or negative)</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Total Price (SAR)</label>
                        <div style="font-size: 24px; font-weight: bold; color: #00aaff; padding: 10px; background: #f8f9fa; border-radius: 5px; text-align: center;">
                            SAR <span id="plan_total_price">0.00</span>
                        </div>
                        <small>Base price + Price modifier</small>
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closePlanModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div id="laundryStaffModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 id="laundryStaffModalTitle">Add New Laundry Staff</h3>
                <span class="close" onclick="closeLaundryStaffModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="laundryStaffForm" method="POST" action="laundry_staff.php">
                    <input type="hidden" id="laundry_staff_id" name="id">
                    <input type="hidden" name="action" id="laundry_action" value="add">
                    
                    <div class="form-group">
                        <label>Name *</label>
                        <input type="text" name="name" id="laundry_name" required placeholder="Enter staff name">
                    </div>
                    
                    <div class="form-group">
                        <label>Email *</label>
                        <input type="email" name="email" id="laundry_email" required placeholder="staff@allura.com">
                    </div>
                    
                    <div class="form-group">
                        <label>Phone *</label>
                        <input type="tel" name="phone" id="laundry_phone" required placeholder="05xxxxxxxx">
                    </div>
                    
                    <div class="form-group" id="password_group">
                        <label>Password *</label>
                        <input type="password" name="password" id="laundry_password" placeholder="Enter password">
                        <small>Leave empty to keep current password (when editing)</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Status *</label>
                        <select name="status" id="laundry_status" required>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" onclick="closeLaundryStaffModal()">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Staff</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        window.chartData = {
            labels: <?php echo json_encode($chart_labels); ?>,
            data: <?php echo json_encode($chart_data); ?>
        };
        
        function showAddLaundryStaffModal() {
            document.getElementById('laundryStaffModalTitle').textContent = 'Add New Laundry Staff';
            document.getElementById('laundry_action').value = 'add';
            document.getElementById('laundry_staff_id').value = '';
            document.getElementById('laundryStaffForm').reset();
            document.getElementById('laundry_password').required = true;
            document.getElementById('laundryStaffModal').style.display = 'block';
        }
        
        function editLaundryStaff(staff) {
            document.getElementById('laundryStaffModalTitle').textContent = 'Edit Laundry Staff';
            document.getElementById('laundry_action').value = 'edit';
            document.getElementById('laundry_staff_id').value = staff.id;
            document.getElementById('laundry_name').value = staff.name;
            document.getElementById('laundry_email').value = staff.email;
            document.getElementById('laundry_phone').value = staff.phone;
            document.getElementById('laundry_status').value = staff.status;
            document.getElementById('laundry_password').required = false;
            document.getElementById('laundry_password').value = '';
            document.getElementById('laundryStaffModal').style.display = 'block';
        }
        
        function closeLaundryStaffModal() {
            document.getElementById('laundryStaffModal').style.display = 'none';
            document.getElementById('laundryStaffForm').reset();
        }
        
        function deleteLaundryStaff(id, name) {
            if (confirm('Are you sure you want to delete ' + name + '? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = 'laundry_staff.php';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'delete';
                
                const idInput = document.createElement('input');
                idInput.type = 'hidden';
                idInput.name = 'id';
                idInput.value = id;
                
                form.appendChild(actionInput);
                form.appendChild(idInput);
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function showLocation(orderId, address, latitude, longitude) {
            const locationModal = document.createElement('div');
            locationModal.className = 'modal';
            locationModal.style.display = 'block';
            locationModal.innerHTML = `
                <div class="modal-content" style="max-width: 600px;">
                    <div class="modal-header">
                        <h3>Customer Location - Order #${orderId}</h3>
                        <span class="close" onclick="this.closest('.modal').remove()">&times;</span>
                    </div>
                    <div class="modal-body">
                        <p><strong>Address:</strong> ${address}</p>
                        <p><strong>Coordinates:</strong> ${latitude}, ${longitude}</p>
                        <div style="margin-top: 15px;">
                            <a href="https://www.google.com/maps?q=${latitude},${longitude}" target="_blank" class="btn" style="margin-right: 10px;">
                                <i class="fas fa-external-link-alt"></i> Open in Google Maps
                            </a>
                            <button onclick="navigator.clipboard.writeText('${latitude}, ${longitude}')" class="btn btn-secondary">
                                <i class="fas fa-copy"></i> Copy Coordinates
                            </button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(locationModal);
        }
        
        window.onclick = function(event) {
            const modal = document.getElementById('laundryStaffModal');
            if (event.target == modal) {
                closeLaundryStaffModal();
            }
        }
    </script>
    <script src="../js/dashboard.js"></script>
    <script src="../js/services.js"></script>
    <script src="../js/subscriptions.js"></script>
</body>
</html>