<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in and has Super Admin role
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details and role verification
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Super Admin') {
    header('Location: dashboard.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_service':
                $service_name = trim($_POST['service_name']);
                $category_id = (int)$_POST['category_id'];
                $description = trim($_POST['description']);
                $price = (float)$_POST['price'];
                $unit = trim($_POST['unit']);
                $estimated_hours = (int)$_POST['estimated_hours'];
                $sort_order = (int)$_POST['sort_order'];
                
                $sql_add = "INSERT INTO services (service_name, category_id, description, price, unit, estimated_hours, sort_order) 
                           VALUES (?, ?, ?, ?, ?, ?, ?)";
                $stmt_add = $conn->prepare($sql_add);
                $stmt_add->bind_param("sisdsii", $service_name, $category_id, $description, $price, $unit, $estimated_hours, $sort_order);
                
                if ($stmt_add->execute()) {
                    $message = "Service added successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error adding service: " . $conn->error;
                    $message_type = "error";
                }
                break;
                
            case 'update_service':
                $service_id = (int)$_POST['service_id'];
                $service_name = trim($_POST['edit_service_name']);
                $category_id = (int)$_POST['edit_category_id'];
                $description = trim($_POST['edit_description']);
                $price = (float)$_POST['edit_price'];
                $unit = trim($_POST['edit_unit']);
                $estimated_hours = (int)$_POST['edit_estimated_hours'];
                $sort_order = (int)$_POST['edit_sort_order'];
                $is_active = isset($_POST['edit_is_active']) ? 1 : 0;
                
                $sql_update = "UPDATE services SET 
                              service_name = ?, category_id = ?, description = ?, 
                              price = ?, unit = ?, estimated_hours = ?, 
                              sort_order = ?, is_active = ?
                              WHERE service_id = ?";
                $stmt_update = $conn->prepare($sql_update);
                $stmt_update->bind_param("sisdsiibi", $service_name, $category_id, $description, $price, $unit, $estimated_hours, $sort_order, $is_active, $service_id);
                
                if ($stmt_update->execute()) {
                    $message = "Service updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error updating service: " . $conn->error;
                    $message_type = "error";
                }
                break;
                
            case 'add_category':
                $category_name = trim($_POST['category_name']);
                $category_description = trim($_POST['category_description']);
                $sort_order = (int)$_POST['category_sort_order'];
                
                $sql_add_cat = "INSERT INTO service_categories (category_name, description, sort_order) VALUES (?, ?, ?)";
                $stmt_add_cat = $conn->prepare($sql_add_cat);
                $stmt_add_cat->bind_param("ssi", $category_name, $category_description, $sort_order);
                
                if ($stmt_add_cat->execute()) {
                    $message = "Service category added successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error adding category: " . $conn->error;
                    $message_type = "error";
                }
                break;
        }
    }
}

// Get service categories
$sql_categories = "SELECT * FROM service_categories ORDER BY sort_order, category_name";
$result_categories = $conn->query($sql_categories);

// Get services with category information and usage statistics
$sql_services = "SELECT 
    s.*,
    sc.category_name,
    COALESCE(usage_stats.order_count, 0) as usage_count,
    COALESCE(usage_stats.total_revenue, 0) as total_revenue,
    COALESCE(usage_stats.total_quantity, 0) as total_quantity,
    COALESCE(usage_stats.last_used, NULL) as last_used
FROM services s
LEFT JOIN service_categories sc ON s.category_id = sc.category_id
LEFT JOIN (
    SELECT 
        oi.service_id,
        COUNT(DISTINCT oi.order_id) as order_count,
        SUM(oi.total_price) as total_revenue,
        SUM(oi.quantity) as total_quantity,
        MAX(o.order_date) as last_used
    FROM order_items oi
    INNER JOIN orders o ON oi.order_id = o.order_id
    WHERE o.status != 'CANCELLED'
    GROUP BY oi.service_id
) usage_stats ON s.service_id = usage_stats.service_id
ORDER BY s.sort_order, s.service_name";

$result_services = $conn->query($sql_services);

// Get summary statistics
$sql_summary = "SELECT 
    COUNT(*) as total_services,
    COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_services,
    COUNT(CASE WHEN is_active = 0 THEN 1 END) as inactive_services,
    COALESCE(AVG(price), 0) as avg_price,
    COALESCE(MIN(price), 0) as min_price,
    COALESCE(MAX(price), 0) as max_price
FROM services";
$summary = $conn->query($sql_summary)->fetch_assoc();

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Service Types - Laundry Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Header Section */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 1.875rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .header-subtitle {
            opacity: 0.9;
            font-size: 1rem;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn-primary {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.2s ease;
            cursor: pointer;
        }
        
        .btn-primary:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            transform: translateY(-1px);
        }
        
        /* Alert Messages */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border: none;
            font-weight: 500;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        /* Statistics Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.025em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        /* Tab Navigation */
        .nav-tabs {
            background: white;
            border-radius: 12px 12px 0 0;
            border: 1px solid #e2e8f0;
            border-bottom: none;
            padding: 1rem 1.5rem 0;
        }
        
        .nav-tab {
            padding: 0.75rem 1.5rem;
            border: none;
            background: transparent;
            color: #64748b;
            font-weight: 600;
            cursor: pointer;
            border-radius: 8px 8px 0 0;
            margin-right: 0.5rem;
            transition: all 0.2s ease;
        }
        
        .nav-tab.active {
            background: #f8fafc;
            color: #059669;
            border-bottom: 2px solid #059669;
        }
        
        .nav-tab:hover {
            background: #f1f5f9;
            color: #374151;
        }
        
        /* Tab Content */
        .tab-content {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 0 0 12px 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .tab-pane {
            display: none;
        }
        
        .tab-pane.active {
            display: block;
        }
        
        /* Forms */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .form-control {
            width: 100%;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: border-color 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #059669;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
            outline: none;
        }
        
        .btn-success {
            background: #059669;
            border: 1px solid #059669;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-success:hover {
            background: #047857;
            border-color: #047857;
            transform: translateY(-1px);
        }
        
        .btn-warning {
            background: #d97706;
            border: 1px solid #d97706;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-warning:hover {
            background: #b45309;
            border-color: #b45309;
        }
        
        .btn-danger {
            background: #dc2626;
            border: 1px solid #dc2626;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-danger:hover {
            background: #b91c1c;
            border-color: #b91c1c;
        }
        
        /* Services Table */
        .services-table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .services-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .services-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #374151;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .services-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
            vertical-align: middle;
        }
        
        .services-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        
        .category-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            background: #e0e7ff;
            color: #3730a3;
        }
        
        /* Price Display */
        .price-display {
            font-weight: 700;
            font-family: 'Courier New', monospace;
            color: #059669;
            font-size: 1rem;
        }
        
        /* Usage Statistics */
        .usage-stats {
            font-size: 0.75rem;
            color: #64748b;
            line-height: 1.4;
        }
        
        .usage-stat {
            margin-bottom: 0.25rem;
        }
        
        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        
        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            margin-bottom: 1.5rem;
        }
        
        .modal-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .modal-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
        }
        
        .btn-secondary {
            background: #64748b;
            border: 1px solid #64748b;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: #475569;
            border-color: #475569;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .services-table-container {
                overflow-x: auto;
            }
            
            .services-table {
                min-width: 800px;
            }
            
            .modal-content {
                width: 95%;
                padding: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="header-content">
                            <div class="header-title">
                                <h1>Service Types Management</h1>
                                <div class="header-subtitle">
                                    Manage laundry services, categories, and pricing
                                </div>
                            </div>
                            <div class="header-actions">
                                <button onclick="openAddServiceModal()" class="btn-primary">
                                    <i class="ph-plus"></i> Add Service
                                </button>
                                <button onclick="openAddCategoryModal()" class="btn-primary">
                                    <i class="ph-folder-plus"></i> Add Category
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (!empty($message)): ?>
                    <div class="alert alert-<?php echo $message_type; ?>">
                        <?php echo htmlspecialchars($message); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-title">Total Services</div>
                            <div class="stat-value"><?php echo number_format($summary['total_services']); ?></div>
                            <div class="stat-change">All service types</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Active Services</div>
                            <div class="stat-value"><?php echo number_format($summary['active_services']); ?></div>
                            <div class="stat-change">Currently available</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Average Price</div>
                            <div class="stat-value">KES <?php echo number_format($summary['avg_price']); ?></div>
                            <div class="stat-change">Per service unit</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Price Range</div>
                            <div class="stat-value">
                                <span style="font-size: 1.25rem;">KES <?php echo number_format($summary['min_price']); ?></span>
                                <span style="font-size: 1rem; color: #64748b;"> - </span>
                                <span style="font-size: 1.25rem;">KES <?php echo number_format($summary['max_price']); ?></span>
                            </div>
                            <div class="stat-change">Min - Max pricing</div>
                        </div>
                    </div>

                    <!-- Services Management Table -->
                    <div class="services-table-container">
                        <div class="table-header">
                            <h3 class="table-title">All Services</h3>
                            <div style="font-size: 0.875rem; color: #64748b;">
                                <?php echo $result_services->num_rows; ?> services configured
                            </div>
                        </div>
                        
                        <table class="services-table">
                            <thead>
                                <tr>
                                    <th>Service Details</th>
                                    <th>Category</th>
                                    <th>Pricing</th>
                                    <th>Turnaround</th>
                                    <th>Usage Statistics</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($service = $result_services->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight: 700; color: #1e293b; margin-bottom: 0.25rem;">
                                            <?php echo htmlspecialchars($service['service_name']); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.8rem; line-height: 1.4;">
                                            <?php echo htmlspecialchars($service['description'] ?: 'No description'); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem; margin-top: 0.25rem;">
                                            ID: <?php echo $service['service_id']; ?> | Sort: <?php echo $service['sort_order']; ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <span class="category-badge">
                                            <?php echo htmlspecialchars($service['category_name'] ?: 'Uncategorized'); ?>
                                        </span>
                                    </td>
                                    
                                    <td>
                                        <div class="price-display">
                                            KES <?php echo number_format($service['price'], 2); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            per <?php echo htmlspecialchars($service['unit']); ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo $service['estimated_hours']; ?> hours
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            Estimated time
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <div class="usage-stats">
                                            <div class="usage-stat">
                                                <strong><?php echo number_format($service['usage_count']); ?></strong> orders
                                            </div>
                                            <div class="usage-stat">
                                                <strong><?php echo number_format($service['total_quantity']); ?></strong> pieces
                                            </div>
                                            <div class="usage-stat">
                                                <strong>KES <?php echo number_format($service['total_revenue']); ?></strong> revenue
                                            </div>
                                            <?php if ($service['last_used']): ?>
                                            <div class="usage-stat">
                                                Last: <?php echo date('M j, Y', strtotime($service['last_used'])); ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <span class="status-badge status-<?php echo $service['is_active'] ? 'active' : 'inactive'; ?>">
                                            <?php echo $service['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    
                                    <td>
                                        <div style="display: flex; gap: 0.5rem;">
                                            <button onclick="editService(<?php echo htmlspecialchars(json_encode($service)); ?>)" 
                                                    class="btn-warning" title="Edit Service">
                                                <i class="ph-pencil"></i>
                                            </button>
                                            <button onclick="toggleServiceStatus(<?php echo $service['service_id']; ?>, <?php echo $service['is_active']; ?>)" 
                                                    class="btn-<?php echo $service['is_active'] ? 'danger' : 'success'; ?>" 
                                                    title="<?php echo $service['is_active'] ? 'Deactivate' : 'Activate'; ?> Service">
                                                <i class="ph-<?php echo $service['is_active'] ? 'eye-slash' : 'eye'; ?>"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Service Modal -->
    <div id="addServiceModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Add New Service</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add_service">
                
                <div class="form-group">
                    <label class="form-label">Service Name</label>
                    <input type="text" name="service_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php 
                        $result_categories->data_seek(0);
                        while($category = $result_categories->fetch_assoc()): 
                        ?>
                        <option value="<?php echo $category['category_id']; ?>">
                            <?php echo htmlspecialchars($category['category_name']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Price (KES)</label>
                        <input type="number" name="price" class="form-control" step="0.01" min="0" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Unit</label>
                        <select name="unit" class="form-control" required>
                            <option value="piece">Piece</option>
                            <option value="set">Set</option>
                            <option value="kg">Kilogram</option>
                            <option value="hour">Hour</option>
                            <option value="service">Service</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Estimated Hours</label>
                        <input type="number" name="estimated_hours" class="form-control" min="1" value="24" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="sort_order" class="form-control" min="0" value="0" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="Optional service description"></textarea>
                </div>
                
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('addServiceModal')" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn-success">Add Service</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Service Modal -->
    <div id="editServiceModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Edit Service</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_service">
                <input type="hidden" name="service_id" id="edit_service_id">
                
                <div class="form-group">
                    <label class="form-label">Service Name</label>
                    <input type="text" name="edit_service_name" id="edit_service_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Category</label>
                    <select name="edit_category_id" id="edit_category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php 
                        $result_categories->data_seek(0);
                        while($category = $result_categories->fetch_assoc()): 
                        ?>
                        <option value="<?php echo $category['category_id']; ?>">
                            <?php echo htmlspecialchars($category['category_name']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Price (KES)</label>
                        <input type="number" name="edit_price" id="edit_price" class="form-control" step="0.01" min="0" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Unit</label>
                        <select name="edit_unit" id="edit_unit" class="form-control" required>
                            <option value="piece">Piece</option>
                            <option value="set">Set</option>
                            <option value="kg">Kilogram</option>
                            <option value="hour">Hour</option>
                            <option value="service">Service</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Estimated Hours</label>
                        <input type="number" name="edit_estimated_hours" id="edit_estimated_hours" class="form-control" min="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="edit_sort_order" id="edit_sort_order" class="form-control" min="0" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="edit_description" id="edit_description" class="form-control" rows="3"></textarea>
                </div>
                
                <div class="form-group">
                    <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
                        <input type="checkbox" name="edit_is_active" id="edit_is_active" style="transform: scale(1.2);">
                        <span class="form-label" style="margin: 0;">Service is active</span>
                    </label>
                </div>
                
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('editServiceModal')" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn-success">Update Service</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Category Modal -->
    <div id="addCategoryModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Add Service Category</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add_category">
                
                <div class="form-group">
                    <label class="form-label">Category Name</label>
                    <input type="text" name="category_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="category_description" class="form-control" rows="3" placeholder="Optional category description"></textarea>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Sort Order</label>
                    <input type="number" name="category_sort_order" class="form-control" min="0" value="0" required>
                </div>
                
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('addCategoryModal')" class="btn-secondary">Cancel</button>
                    <button type="submit" class="btn-success">Add Category</button>
                </div>
            </form>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Modal functions
        function openAddServiceModal() {
            document.getElementById('addServiceModal').style.display = 'flex';
        }
        
        function openAddCategoryModal() {
            document.getElementById('addCategoryModal').style.display = 'flex';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function editService(service) {
            document.getElementById('edit_service_id').value = service.service_id;
            document.getElementById('edit_service_name').value = service.service_name;
            document.getElementById('edit_category_id').value = service.category_id;
            document.getElementById('edit_price').value = service.price;
            document.getElementById('edit_unit').value = service.unit;
            document.getElementById('edit_estimated_hours').value = service.estimated_hours;
            document.getElementById('edit_sort_order').value = service.sort_order;
            document.getElementById('edit_description').value = service.description || '';
            document.getElementById('edit_is_active').checked = service.is_active == 1;
            
            document.getElementById('editServiceModal').style.display = 'flex';
        }
        
        function toggleServiceStatus(serviceId, currentStatus) {
            const action = currentStatus ? 'deactivate' : 'activate';
            if (confirm(`Are you sure you want to ${action} this service?`)) {
                // Create a form to submit the toggle action
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="toggle_status">
                    <input type="hidden" name="service_id" value="${serviceId}">
                    <input type="hidden" name="new_status" value="${currentStatus ? 0 : 1}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // Close modals when clicking outside
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('modal-overlay')) {
                e.target.style.display = 'none';
            }
        });
        
        // Handle toggle status action
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'toggle_status') {
            $service_id = (int)$_POST['service_id'];
            $new_status = (int)$_POST['new_status'];
            
            $sql_toggle = "UPDATE services SET is_active = ? WHERE service_id = ?";
            $stmt_toggle = $conn->prepare($sql_toggle);
            $stmt_toggle->bind_param("ii", $new_status, $service_id);
            
            if ($stmt_toggle->execute()) {
                echo "window.location.reload();";
            }
        }
        ?>
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>