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

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

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

$user_id = $_SESSION['user_id'];

// Fetch user details
$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) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_service':
                $service_code = trim($_POST['service_code']);
                $service_name = trim($_POST['service_name']);
                $description = trim($_POST['description']);
                $service_category = $_POST['service_category'];
                $transit_days_min = intval($_POST['transit_days_min']);
                $transit_days_max = intval($_POST['transit_days_max']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                // Check if service code already exists
                $check_sql = "SELECT service_id FROM service_types WHERE service_code = ?";
                $check_stmt = $conn->prepare($check_sql);
                $check_stmt->bind_param("s", $service_code);
                $check_stmt->execute();
                
                if ($check_stmt->get_result()->num_rows > 0) {
                    $message = "Service code already exists!";
                    $message_type = "danger";
                } else {
                    $insert_sql = "INSERT INTO service_types (service_code, service_name, description, service_category, transit_days_min, transit_days_max, is_active) 
                                   VALUES (?, ?, ?, ?, ?, ?, ?)";
                    $insert_stmt = $conn->prepare($insert_sql);
                    $insert_stmt->bind_param("ssssiii", $service_code, $service_name, $description, $service_category, $transit_days_min, $transit_days_max, $is_active);
                    
                    if ($insert_stmt->execute()) {
                        $message = "Service added successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error adding service: " . $conn->error;
                        $message_type = "danger";
                    }
                }
                break;

            case 'update_service':
                $service_id = intval($_POST['service_id']);
                $service_code = trim($_POST['service_code']);
                $service_name = trim($_POST['service_name']);
                $description = trim($_POST['description']);
                $service_category = $_POST['service_category'];
                $transit_days_min = intval($_POST['transit_days_min']);
                $transit_days_max = intval($_POST['transit_days_max']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                $update_sql = "UPDATE service_types SET 
                               service_code = ?, service_name = ?, description = ?, 
                               service_category = ?, transit_days_min = ?, transit_days_max = ?, 
                               is_active = ? 
                               WHERE service_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("ssssiii i", $service_code, $service_name, $description, $service_category, 
                                       $transit_days_min, $transit_days_max, $is_active, $service_id);
                
                if ($update_stmt->execute()) {
                    $message = "Service updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error updating service: " . $conn->error;
                    $message_type = "danger";
                }
                break;

            case 'toggle_status':
                $service_id = intval($_POST['service_id']);
                $new_status = intval($_POST['new_status']);
                
                $toggle_sql = "UPDATE service_types SET is_active = ? WHERE service_id = ?";
                $toggle_stmt = $conn->prepare($toggle_sql);
                $toggle_stmt->bind_param("ii", $new_status, $service_id);
                
                if ($toggle_stmt->execute()) {
                    echo json_encode(['success' => true]);
                    exit;
                } else {
                    echo json_encode(['success' => false, 'error' => $conn->error]);
                    exit;
                }
                break;

            case 'delete_service':
                $service_id = intval($_POST['service_id']);
                
                // Check if service is being used in shipments
                $usage_check = "SELECT COUNT(*) as usage_count FROM shipments WHERE service_id = ?";
                $usage_stmt = $conn->prepare($usage_check);
                $usage_stmt->bind_param("i", $service_id);
                $usage_stmt->execute();
                $usage_result = $usage_stmt->get_result()->fetch_assoc();
                
                if ($usage_result['usage_count'] > 0) {
                    echo json_encode(['success' => false, 'error' => 'Cannot delete service that is being used in shipments. Consider deactivating instead.']);
                    exit;
                }
                
                $delete_sql = "DELETE FROM service_types WHERE service_id = ?";
                $delete_stmt = $conn->prepare($delete_sql);
                $delete_stmt->bind_param("i", $service_id);
                
                if ($delete_stmt->execute()) {
                    echo json_encode(['success' => true]);
                    exit;
                } else {
                    echo json_encode(['success' => false, 'error' => $conn->error]);
                    exit;
                }
                break;
        }
    }
}

// Get filter parameters
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// Build WHERE clause for filters
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($category_filter)) {
    $where_conditions[] = "service_category = ?";
    $params[] = $category_filter;
    $param_types .= 's';
}

if (!empty($status_filter)) {
    $where_conditions[] = "is_active = ?";
    $params[] = ($status_filter === 'active') ? 1 : 0;
    $param_types .= 'i';
}

if (!empty($search)) {
    $where_conditions[] = "(service_code LIKE ? OR service_name LIKE ? OR description LIKE ?)";
    $search_param = '%' . $search . '%';
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'sss';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get services with usage statistics
$services_sql = "SELECT 
    st.*,
    COUNT(s.shipment_id) as usage_count,
    SUM(s.total_charges) as total_revenue,
    AVG(s.total_charges) as avg_revenue,
    COUNT(CASE WHEN s.status = 'DELIVERED' THEN 1 END) as delivered_count,
    MAX(s.booking_date) as last_used_date
FROM service_types st
LEFT JOIN shipments s ON st.service_id = s.service_id
$where_clause
GROUP BY st.service_id, st.service_code, st.service_name, st.description, 
         st.service_category, st.transit_days_min, st.transit_days_max, st.is_active, st.created_at
ORDER BY st.service_category, st.service_name";

if (!empty($params)) {
    $services_stmt = $conn->prepare($services_sql);
    $services_stmt->bind_param($param_types, ...$params);
    $services_stmt->execute();
    $services_result = $services_stmt->get_result();
} else {
    $services_result = $conn->query($services_sql);
}

// Get service categories for filter
$categories = ['AIR', 'SEA', 'ROAD', 'EXPRESS', 'COURIER'];

// Get service statistics
$stats_sql = "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,
    COUNT(DISTINCT service_category) as total_categories
FROM service_types";
$stats_result = $conn->query($stats_sql);
$service_stats = $stats_result->fetch_assoc();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Service Configuration - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .service-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            margin-bottom: 1rem;
            transition: all 0.2s ease;
            overflow: hidden;
        }
        
        .service-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .service-header {
            padding: 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        }
        
        .service-body {
            padding: 1.5rem;
        }
        
        .service-category-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .category-air { background: #dbeafe; color: #1d4ed8; }
        .category-sea { background: #dcfce7; color: #166534; }
        .category-road { background: #fef3c7; color: #d97706; }
        .category-express { background: #fee2e2; color: #991b1b; }
        .category-courier { background: #e0e7ff; color: #5b21b6; }
        
        .status-toggle {
            cursor: pointer;
        }
        
        .status-active {
            background: #dcfce7;
            color: #166534;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-inactive {
            background: #fee2e2;
            color: #991b1b;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .filters-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .service-usage {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #f1f5f9;
        }
        
        .usage-stats {
            display: flex;
            gap: 1rem;
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .service-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .form-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .section-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .performance-indicator {
            width: 100%;
            height: 4px;
            background: #f1f5f9;
            border-radius: 2px;
            margin-top: 0.5rem;
            overflow: hidden;
        }
        
        .performance-bar {
            height: 100%;
            border-radius: 2px;
            transition: width 0.3s ease;
        }
        
        .performance-excellent { background: #10b981; }
        .performance-good { background: #3b82f6; }
        .performance-average { background: #f59e0b; }
        .performance-poor { background: #ef4444; }
        
        @media (max-width: 768px) {
            .service-header,
            .service-body {
                padding: 1rem;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .service-usage {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
            
            .usage-stats {
                flex-direction: column;
                gap: 0.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 Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Service Configuration</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="shipments.php">Shipments</a></li>
                                        <li class="breadcrumb-item active">Service Configuration</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value" style="color: #3b82f6;"><?php echo number_format($service_stats['total_services']); ?></div>
                            <div class="stat-label">Total Services</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #10b981;"><?php echo number_format($service_stats['active_services']); ?></div>
                            <div class="stat-label">Active Services</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #f59e0b;"><?php echo number_format($service_stats['inactive_services']); ?></div>
                            <div class="stat-label">Inactive Services</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #8b5cf6;"><?php echo number_format($service_stats['total_categories']); ?></div>
                            <div class="stat-label">Categories</div>
                        </div>
                    </div>

                    <!-- Add New Service Form -->
                    <div class="form-section" id="addServiceForm" style="display: none;">
                        <div class="section-header">
                            <h5 class="mb-0">Add New Service</h5>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="hideAddForm()">
                                <i class="bx bx-x"></i> Cancel
                            </button>
                        </div>
                        
                        <form method="POST">
                            <input type="hidden" name="action" value="add_service">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Service Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="service_code" required maxlength="10" style="text-transform: uppercase;">
                                        <small class="text-muted">Unique code (e.g., AIR-EXP)</small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label class="form-label">Service Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="service_name" required maxlength="100">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Category <span class="text-danger">*</span></label>
                                        <select class="form-select" name="service_category" required>
                                            <option value="">Select Category</option>
                                            <?php foreach($categories as $category): ?>
                                            <option value="<?php echo $category; ?>"><?php echo $category; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="mb-3">
                                        <label class="form-label">Status</label>
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" name="is_active" checked>
                                            <label class="form-check-label">Active</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea class="form-control" name="description" rows="3" maxlength="500"></textarea>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Min Transit Days</label>
                                        <input type="number" class="form-control" name="transit_days_min" min="0" max="365">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Max Transit Days</label>
                                        <input type="number" class="form-control" name="transit_days_max" min="0" max="365">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-end gap-2">
                                <button type="button" class="btn btn-outline-secondary" onclick="hideAddForm()">Cancel</button>
                                <button type="submit" class="btn btn-primary">
                                    <i class="bx bx-plus"></i> Add Service
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Filters and Actions -->
                    <div class="filters-section">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0">Service Management</h5>
                            <button type="button" class="btn btn-primary" onclick="showAddForm()">
                                <i class="bx bx-plus"></i> Add New Service
                            </button>
                        </div>
                        
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Service code, name, or description...">
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Category</label>
                                <select class="form-select" name="category">
                                    <option value="">All Categories</option>
                                    <?php foreach($categories as $category): ?>
                                    <option value="<?php echo $category; ?>" <?php echo $category_filter === $category ? 'selected' : ''; ?>>
                                        <?php echo $category; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Status</option>
                                    <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-outline-primary d-block w-100">Filter</button>
                            </div>
                        </form>
                    </div>

                    <!-- Services List -->
                    <div class="row">
                        <div class="col-12">
                            <?php if ($services_result->num_rows > 0): ?>
                                <?php while($service = $services_result->fetch_assoc()): ?>
                                <?php 
                                $delivery_rate = $service['usage_count'] > 0 ? 
                                    round(($service['delivered_count'] / $service['usage_count']) * 100, 1) : 0;
                                $performance_class = $delivery_rate >= 95 ? 'excellent' : 
                                    ($delivery_rate >= 85 ? 'good' : 
                                    ($delivery_rate >= 70 ? 'average' : 'poor'));
                                ?>
                                <div class="service-card">
                                    <div class="service-header">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h5 class="mb-1"><?php echo htmlspecialchars($service['service_name']); ?></h5>
                                                <div class="d-flex align-items-center gap-2">
                                                    <span class="badge bg-secondary"><?php echo $service['service_code']; ?></span>
                                                    <span class="service-category-badge category-<?php echo strtolower($service['service_category']); ?>">
                                                        <?php echo $service['service_category']; ?>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <span class="status-toggle <?php echo $service['is_active'] ? 'status-active' : 'status-inactive'; ?>" 
                                                      onclick="toggleServiceStatus(<?php echo $service['service_id']; ?>, <?php echo $service['is_active'] ? 0 : 1; ?>)">
                                                    <?php echo $service['is_active'] ? 'ACTIVE' : 'INACTIVE'; ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="service-body">
                                        <?php if ($service['description']): ?>
                                        <p class="text-muted mb-3"><?php echo htmlspecialchars($service['description']); ?></p>
                                        <?php endif; ?>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="row">
                                                    <div class="col-6">
                                                        <small class="text-muted">Transit Time</small>
                                                        <div class="fw-bold">
                                                            <?php if ($service['transit_days_min'] && $service['transit_days_max']): ?>
                                                                <?php echo $service['transit_days_min']; ?> - <?php echo $service['transit_days_max']; ?> days
                                                            <?php elseif ($service['transit_days_max']): ?>
                                                                Up to <?php echo $service['transit_days_max']; ?> days
                                                            <?php else: ?>
                                                                Not specified
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                    <div class="col-6">
                                                        <small class="text-muted">Usage Count</small>
                                                        <div class="fw-bold"><?php echo number_format($service['usage_count']); ?> shipments</div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <div class="row">
                                                    <div class="col-6">
                                                        <small class="text-muted">Total Revenue</small>
                                                        <div class="fw-bold text-success">KES <?php echo number_format($service['total_revenue'] ?? 0); ?></div>
                                                    </div>
                                                    <div class="col-6">
                                                        <small class="text-muted">Avg Revenue</small>
                                                        <div class="fw-bold">KES <?php echo number_format($service['avg_revenue'] ?? 0); ?></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <?php if ($service['usage_count'] > 0): ?>
                                        <div class="mt-3">
                                            <div class="d-flex justify-content-between align-items-center mb-1">
                                                <small class="text-muted">Delivery Performance</small>
                                                <small class="fw-bold"><?php echo $delivery_rate; ?>%</small>
                                            </div>
                                            <div class="performance-indicator">
                                                <div class="performance-bar performance-<?php echo $performance_class; ?>" 
                                                     style="width: <?php echo $delivery_rate; ?>%"></div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="service-usage">
                                            <div class="usage-stats">
                                                <?php if ($service['last_used_date']): ?>
                                                <span>Last used: <?php echo date('M j, Y', strtotime($service['last_used_date'])); ?></span>
                                                <?php endif; ?>
                                                <span>Created: <?php echo date('M j, Y', strtotime($service['created_at'])); ?></span>
                                                <span>Delivered: <?php echo number_format($service['delivered_count']); ?></span>
                                            </div>
                                            
                                            <div class="service-actions">
                                                <button type="button" class="btn btn-outline-primary btn-sm" 
                                                        onclick="editService(<?php echo $service['service_id']; ?>)">
                                                    <i class="bx bx-edit"></i> Edit
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                        onclick="viewServiceAnalytics(<?php echo $service['service_id']; ?>)">
                                                    <i class="bx bx-chart"></i> Analytics
                                                </button>
                                                <?php if ($service['usage_count'] == 0): ?>
                                                <button type="button" class="btn btn-outline-danger btn-sm" 
                                                        onclick="deleteService(<?php echo $service['service_id']; ?>, '<?php echo htmlspecialchars($service['service_name']); ?>')">
                                                    <i class="bx bx-trash"></i> Delete
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <div class="mb-3">
                                        <i class="bx bx-package" style="font-size: 4rem; color: #64748b;"></i>
                                    </div>
                                    <h5 class="text-muted">No services found</h5>
                                    <p class="text-muted">Start by adding your first service type.</p>
                                    <button type="button" class="btn btn-primary" onclick="showAddForm()">
                                        <i class="bx bx-plus"></i> Add Service
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Edit Service Modal -->
    <div class="modal fade" id="editServiceModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Service</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="editServiceForm" method="POST">
                    <input type="hidden" name="action" value="update_service">
                    <input type="hidden" name="service_id" id="edit_service_id">
                    
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Service Code <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="service_code" id="edit_service_code" required maxlength="10">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Service Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="service_name" id="edit_service_name" required maxlength="100">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Category <span class="text-danger">*</span></label>
                                    <select class="form-select" name="service_category" id="edit_service_category" required>
                                        <?php foreach($categories as $category): ?>
                                        <option value="<?php echo $category; ?>"><?php echo $category; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Status</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                                        <label class="form-check-label">Active</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="description" id="edit_description" rows="3" maxlength="500"></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Min Transit Days</label>
                                    <input type="number" class="form-control" name="transit_days_min" id="edit_transit_days_min" min="0" max="365">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Max Transit Days</label>
                                    <input type="number" class="form-control" name="transit_days_max" id="edit_transit_days_max" min="0" max="365">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bx bx-save"></i> Update Service
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Show/Hide Add Form
        function showAddForm() {
            document.getElementById('addServiceForm').style.display = 'block';
            document.querySelector('input[name="service_code"]').focus();
        }
        
        function hideAddForm() {
            document.getElementById('addServiceForm').style.display = 'none';
            // Reset form
            document.querySelector('#addServiceForm form').reset();
        }
        
        // Toggle Service Status
        function toggleServiceStatus(serviceId, newStatus) {
            if (confirm('Are you sure you want to ' + (newStatus ? 'activate' : 'deactivate') + ' this service?')) {
                fetch('service_configuration.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=toggle_status&service_id=${serviceId}&new_status=${newStatus}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while updating the service status');
                });
            }
        }
        
        // Edit Service
        function editService(serviceId) {
            // Get service data via AJAX
            fetch(`get_service_data.php?id=${serviceId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const service = data.service;
                    
                    document.getElementById('edit_service_id').value = service.service_id;
                    document.getElementById('edit_service_code').value = service.service_code;
                    document.getElementById('edit_service_name').value = service.service_name;
                    document.getElementById('edit_service_category').value = service.service_category;
                    document.getElementById('edit_description').value = service.description || '';
                    document.getElementById('edit_transit_days_min').value = service.transit_days_min || '';
                    document.getElementById('edit_transit_days_max').value = service.transit_days_max || '';
                    document.getElementById('edit_is_active').checked = service.is_active == 1;
                    
                    new bootstrap.Modal(document.getElementById('editServiceModal')).show();
                } else {
                    alert('Error loading service data');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading service data');
            });
        }
        
        // Delete Service
        function deleteService(serviceId, serviceName) {
            if (confirm(`Are you sure you want to delete the service "${serviceName}"? This action cannot be undone.`)) {
                fetch('service_configuration.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=delete_service&service_id=${serviceId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while deleting the service');
                });
            }
        }
        
        // View Service Analytics
        function viewServiceAnalytics(serviceId) {
            window.open(`shipment_analytics.php?service=${serviceId}`, '_blank');
        }
        
        // Form validation
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-uppercase service codes
            document.querySelectorAll('input[name="service_code"]').forEach(input => {
                input.addEventListener('input', function() {
                    this.value = this.value.toUpperCase();
                });
            });
            
            // Validate transit days
            function validateTransitDays(minInput, maxInput) {
                const minVal = parseInt(minInput.value) || 0;
                const maxVal = parseInt(maxInput.value) || 0;
                
                if (minVal > 0 && maxVal > 0 && minVal > maxVal) {
                    maxInput.setCustomValidity('Max days must be greater than or equal to min days');
                } else {
                    maxInput.setCustomValidity('');
                }
            }
            
            // Add validation to all transit day inputs
            document.querySelectorAll('input[name="transit_days_min"]').forEach(input => {
                input.addEventListener('change', function() {
                    const maxInput = this.closest('form').querySelector('input[name="transit_days_max"]');
                    if (maxInput) validateTransitDays(this, maxInput);
                });
            });
            
            document.querySelectorAll('input[name="transit_days_max"]').forEach(input => {
                input.addEventListener('change', function() {
                    const minInput = this.closest('form').querySelector('input[name="transit_days_min"]');
                    if (minInput) validateTransitDays(minInput, this);
                });
            });
            
            // Search functionality
            const searchInput = document.querySelector('input[name="search"]');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        this.closest('form').submit();
                    }
                });
            }
        });
        
        // Bulk operations
        function selectAllServices() {
            const checkboxes = document.querySelectorAll('.service-checkbox');
            const selectAll = document.getElementById('selectAllServices');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            
            updateBulkActions();
        }
        
        function updateBulkActions() {
            const selected = document.querySelectorAll('.service-checkbox:checked').length;
            const bulkActions = document.getElementById('bulkActions');
            
            if (selected > 0) {
                bulkActions.style.display = 'block';
                document.getElementById('selectedCount').textContent = selected;
            } else {
                bulkActions.style.display = 'none';
            }
        }
        
        function performBulkAction(action) {
            const selectedServices = Array.from(document.querySelectorAll('.service-checkbox:checked'))
                .map(cb => cb.value);
            
            if (selectedServices.length === 0) {
                alert('Please select at least one service');
                return;
            }
            
            let confirmMessage = '';
            switch(action) {
                case 'activate':
                    confirmMessage = `Activate ${selectedServices.length} selected services?`;
                    break;
                case 'deactivate':
                    confirmMessage = `Deactivate ${selectedServices.length} selected services?`;
                    break;
                case 'delete':
                    confirmMessage = `Delete ${selectedServices.length} selected services? This cannot be undone.`;
                    break;
            }
            
            if (confirm(confirmMessage)) {
                fetch('bulk_service_actions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: action,
                        service_ids: selectedServices
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(`Successfully ${action}d ${data.affected_count} services`);
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while performing the bulk action');
                });
            }
        }
        
        // Export functions
        function exportServices(format) {
            const params = new URLSearchParams(window.location.search);
            params.set('export', format);
            window.location.href = 'service_configuration.php?' + params.toString();
        }
        
        // Service duplication
        function duplicateService(serviceId) {
            if (confirm('Create a copy of this service?')) {
                fetch('duplicate_service.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `service_id=${serviceId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Service duplicated successfully!');
                        location.reload();
                    } else {
                        alert('Error: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error duplicating service');
                });
            }
        }
        
        // Print functionality
        function printServices() {
            window.print();
        }
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl/Cmd + N for new service
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                showAddForm();
            }
            
            // Escape to hide add form
            if (e.key === 'Escape') {
                hideAddForm();
            }
            
            // Ctrl/Cmd + F for search
            if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
                e.preventDefault();
                document.querySelector('input[name="search"]').focus();
            }
        });
        
        // Auto-save form data to localStorage
        function saveFormData() {
            const formData = new FormData(document.querySelector('#addServiceForm form'));
            const data = {};
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            localStorage.setItem('addServiceFormData', JSON.stringify(data));
        }
        
        function loadFormData() {
            const savedData = localStorage.getItem('addServiceFormData');
            if (savedData) {
                const data = JSON.parse(savedData);
                const form = document.querySelector('#addServiceForm form');
                
                Object.keys(data).forEach(key => {
                    const field = form.querySelector(`[name="${key}"]`);
                    if (field) {
                        if (field.type === 'checkbox') {
                            field.checked = data[key] === 'on';
                        } else {
                            field.value = data[key];
                        }
                    }
                });
            }
        }
        
        // Clear saved form data on successful submission
        document.querySelector('#addServiceForm form').addEventListener('submit', function() {
            localStorage.removeItem('addServiceFormData');
        });
        
        // Performance monitoring
        function trackServicePerformance() {
            const performanceBars = document.querySelectorAll('.performance-bar');
            
            performanceBars.forEach(bar => {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            entry.target.style.width = entry.target.getAttribute('data-width') + '%';
                        }
                    });
                });
                
                observer.observe(bar);
            });
        }
        
        // Initialize performance tracking
        document.addEventListener('DOMContentLoaded', trackServicePerformance);
        
        // Service health check
        function checkServiceHealth() {
            fetch('check_service_health.php')
            .then(response => response.json())
            .then(data => {
                if (data.issues && data.issues.length > 0) {
                    showHealthAlert(data.issues);
                }
            })
            .catch(error => {
                console.error('Health check failed:', error);
            });
        }
        
        function showHealthAlert(issues) {
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-warning alert-dismissible fade show';
            alertDiv.innerHTML = `
                <strong>Service Health Issues Detected:</strong>
                <ul class="mb-0 mt-2">
                    ${issues.map(issue => `<li>${issue}</li>`).join('')}
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.querySelector('.container-fluid').insertBefore(alertDiv, document.querySelector('.stats-grid'));
        }
        
        // Run health check on page load
        setTimeout(checkServiceHealth, 2000);
    </script>
    
    <!-- Print Styles -->
    <style media="print">
        .filters-section, .service-actions, .btn, .page-title-right, .form-section {
            display: none !important;
        }
        
        .service-card {
            break-inside: avoid;
            margin-bottom: 20px;
            border: 1px solid #000;
        }
        
        .service-header {
            background: #f8f9fa !important;
            -webkit-print-color-adjust: exact;
        }
        
        @page {
            margin: 1cm;
        }
    </style>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php
// Handle CSV/Excel export
if (isset($_GET['export'])) {
    $export_format = $_GET['export'];
    
    // Rebuild query for export
    $export_sql = "SELECT 
        st.service_code,
        st.service_name,
        st.description,
        st.service_category,
        st.transit_days_min,
        st.transit_days_max,
        CASE WHEN st.is_active = 1 THEN 'Active' ELSE 'Inactive' END as status,
        COUNT(s.shipment_id) as usage_count,
        SUM(s.total_charges) as total_revenue,
        AVG(s.total_charges) as avg_revenue,
        COUNT(CASE WHEN s.status = 'DELIVERED' THEN 1 END) as delivered_count,
        st.created_at
    FROM service_types st
    LEFT JOIN shipments s ON st.service_id = s.service_id
    $where_clause
    GROUP BY st.service_id, st.service_code, st.service_name, st.description, 
             st.service_category, st.transit_days_min, st.transit_days_max, st.is_active, st.created_at
    ORDER BY st.service_category, st.service_name";
    
    if (!empty($params)) {
        $export_stmt = $conn->prepare($export_sql);
        $export_stmt->bind_param($param_types, ...$params);
        $export_stmt->execute();
        $export_result = $export_stmt->get_result();
    } else {
        $export_result = $conn->query($export_sql);
    }
    
    if ($export_format === 'csv') {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=service_configuration_' . date('Y-m-d') . '.csv');
        
        $output = fopen('php://output', 'w');
        
        // CSV headers
        fputcsv($output, [
            'Service Code',
            'Service Name',
            'Description',
            'Category',
            'Min Transit Days',
            'Max Transit Days',
            'Status',
            'Usage Count',
            'Total Revenue',
            'Average Revenue',
            'Delivered Count',
            'Created Date'
        ]);
        
        // CSV data
        while ($row = $export_result->fetch_assoc()) {
            fputcsv($output, [
                $row['service_code'],
                $row['service_name'],
                $row['description'],
                $row['service_category'],
                $row['transit_days_min'],
                $row['transit_days_max'],
                $row['status'],
                $row['usage_count'],
                $row['total_revenue'],
                $row['avg_revenue'],
                $row['delivered_count'],
                $row['created_at']
            ]);
        }
        
        fclose($output);
        exit;
        
    } elseif ($export_format === 'excel') {
        // For Excel export, you would typically use a library like PhpSpreadsheet
        // For now, we'll export as CSV with Excel-friendly formatting
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename=service_configuration_' . date('Y-m-d') . '.xls');
        
        echo '<table border="1">';
        echo '<tr>';
        echo '<th>Service Code</th><th>Service Name</th><th>Description</th><th>Category</th>';
        echo '<th>Min Transit Days</th><th>Max Transit Days</th><th>Status</th>';
        echo '<th>Usage Count</th><th>Total Revenue</th><th>Average Revenue</th>';
        echo '<th>Delivered Count</th><th>Created Date</th>';
        echo '</tr>';
        
        while ($row = $export_result->fetch_assoc()) {
            echo '<tr>';
            echo '<td>' . htmlspecialchars($row['service_code']) . '</td>';
            echo '<td>' . htmlspecialchars($row['service_name']) . '</td>';
            echo '<td>' . htmlspecialchars($row['description']) . '</td>';
            echo '<td>' . htmlspecialchars($row['service_category']) . '</td>';
            echo '<td>' . $row['transit_days_min'] . '</td>';
            echo '<td>' . $row['transit_days_max'] . '</td>';
            echo '<td>' . $row['status'] . '</td>';
            echo '<td>' . $row['usage_count'] . '</td>';
            echo '<td>' . $row['total_revenue'] . '</td>';
            echo '<td>' . $row['avg_revenue'] . '</td>';
            echo '<td>' . $row['delivered_count'] . '</td>';
            echo '<td>' . $row['created_at'] . '</td>';
            echo '</tr>';
        }
        
        echo '</table>';
        exit;
    }
}
?>