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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FINANCE_MANAGER'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$success_message = '';
$error_message = '';

// Handle CSV Import
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['csv_file']['tmp_name'];
        
        $conn->begin_transaction();
        try {
            $handle = fopen($file_tmp, 'r');
            $imported_count = 0;
            $skipped_count = 0;
            
            fgetcsv($handle); // Skip header
            
            while (($data = fgetcsv($handle)) !== FALSE) {
                if (count($data) < 3 || empty($data[1]) || empty($data[3])) {
                    $skipped_count++;
                    continue;
                }
                
                $service_name = trim($data[1]);
                $service_category = trim($data[2]);
                $base_price = str_replace([',', '"'], '', trim($data[3]));
                
                $service_type = 'PROCEDURE';
                if (stripos($service_category, 'Investigation') !== false) {
                    $service_type = 'TEST';
                } elseif (stripos($service_category, 'Consultation') !== false) {
                    $service_type = 'CONSULTATION';
                }
                
                $check_sql = "SELECT pricing_id FROM service_pricing WHERE service_name = ? AND is_active = 1";
                $check_stmt = $conn->prepare($check_sql);
                $check_stmt->bind_param('s', $service_name);
                $check_stmt->execute();
                
                if ($check_stmt->get_result()->num_rows > 0) {
                    $skipped_count++;
                    continue;
                }
                
                $insert_sql = "INSERT INTO service_pricing (
                    service_type, service_id, service_name, base_price, 
                    insurance_price, corporate_price, emergency_surcharge, 
                    weekend_surcharge, effective_from, is_active, created_at
                ) VALUES (?, 0, ?, ?, NULL, NULL, 0.00, 0.00, CURDATE(), 1, NOW())";
                
                $insert_stmt = $conn->prepare($insert_sql);
                $insert_stmt->bind_param('ssd', $service_type, $service_name, $base_price);
                
                if ($insert_stmt->execute()) {
                    $imported_count++;
                }
            }
            
            fclose($handle);
            $conn->commit();
            
            $success_message = "CSV Import completed: {$imported_count} services imported, {$skipped_count} skipped";
            
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Import failed: " . $e->getMessage();
        }
    }
}

// Handle Add Service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_service'])) {
    $service_type = $_POST['service_type'];
    $service_name = trim($_POST['service_name']);
    $base_price = floatval($_POST['base_price']);
    $insurance_price = !empty($_POST['insurance_price']) ? floatval($_POST['insurance_price']) : NULL;
    $corporate_price = !empty($_POST['corporate_price']) ? floatval($_POST['corporate_price']) : NULL;
    $emergency_surcharge = !empty($_POST['emergency_surcharge']) ? floatval($_POST['emergency_surcharge']) : 0.00;
    $weekend_surcharge = !empty($_POST['weekend_surcharge']) ? floatval($_POST['weekend_surcharge']) : 0.00;
    $effective_from = $_POST['effective_from'];
    
    $insert_sql = "INSERT INTO service_pricing (
        service_type, service_id, service_name, base_price, 
        insurance_price, corporate_price, emergency_surcharge, 
        weekend_surcharge, effective_from, is_active, created_at
    ) VALUES (?, 0, ?, ?, ?, ?, ?, ?, ?, 1, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param('ssddddds', 
        $service_type, $service_name, $base_price, 
        $insurance_price, $corporate_price, 
        $emergency_surcharge, $weekend_surcharge, $effective_from
    );
    
    if ($stmt->execute()) {
        $success_message = "Service added successfully!";
    } else {
        $error_message = "Failed to add service";
    }
}

// Handle Update Service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_service'])) {
    $pricing_id = intval($_POST['pricing_id']);
    $service_type = $_POST['service_type'];
    $service_name = trim($_POST['service_name']);
    $base_price = floatval($_POST['base_price']);
    $insurance_price = !empty($_POST['insurance_price']) ? floatval($_POST['insurance_price']) : NULL;
    $corporate_price = !empty($_POST['corporate_price']) ? floatval($_POST['corporate_price']) : NULL;
    $emergency_surcharge = !empty($_POST['emergency_surcharge']) ? floatval($_POST['emergency_surcharge']) : 0.00;
    $weekend_surcharge = !empty($_POST['weekend_surcharge']) ? floatval($_POST['weekend_surcharge']) : 0.00;
    $effective_from = $_POST['effective_from'];
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    $update_sql = "UPDATE service_pricing SET 
        service_type = ?, service_name = ?, base_price = ?, 
        insurance_price = ?, corporate_price = ?, emergency_surcharge = ?, 
        weekend_surcharge = ?, effective_from = ?, is_active = ?
        WHERE pricing_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('ssddddsiii', 
        $service_type, $service_name, $base_price, 
        $insurance_price, $corporate_price, 
        $emergency_surcharge, $weekend_surcharge, $effective_from,
        $is_active, $pricing_id
    );
    
    if ($stmt->execute()) {
        $success_message = "Service updated successfully!";
    } else {
        $error_message = "Failed to update service";
    }
}

// Handle Delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $pricing_id = intval($_GET['delete']);
    $delete_sql = "UPDATE service_pricing SET is_active = 0 WHERE pricing_id = ?";
    $stmt = $conn->prepare($delete_sql);
    $stmt->bind_param('i', $pricing_id);
    
    if ($stmt->execute()) {
        header("Location: manage_services.php?success=deleted");
        exit();
    }
}

// Filters
$service_type_filter = isset($_GET['service_type']) ? $_GET['service_type'] : '';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'active';

$where_clauses = [];
$params = [];
$types = '';

if (!empty($service_type_filter)) {
    $where_clauses[] = "service_type = ?";
    $params[] = $service_type_filter;
    $types .= 's';
}

if (!empty($search_query)) {
    $where_clauses[] = "service_name LIKE ?";
    $params[] = "%{$search_query}%";
    $types .= 's';
}

if ($status_filter === 'active') {
    $where_clauses[] = "is_active = 1";
} elseif ($status_filter === 'inactive') {
    $where_clauses[] = "is_active = 0";
}

$where_sql = !empty($where_clauses) ? "WHERE " . implode(" AND ", $where_clauses) : "";

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

$count_sql = "SELECT COUNT(*) as total FROM service_pricing {$where_sql}";
if (!empty($params)) {
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param($types, ...$params);
    $count_stmt->execute();
    $total_records = $count_stmt->get_result()->fetch_assoc()['total'];
} else {
    $total_records = $conn->query($count_sql)->fetch_assoc()['total'];
}
$total_pages = ceil($total_records / $per_page);

$services_sql = "SELECT * FROM service_pricing {$where_sql} 
                ORDER BY service_type, service_name 
                LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$types .= 'ii';

$services_stmt = $conn->prepare($services_sql);
if (!empty($params)) {
    $services_stmt->bind_param($types, ...$params);
}
$services_stmt->execute();
$services = $services_stmt->get_result();

// Statistics
$stats_sql = "SELECT 
    COUNT(*) as total_services,
    COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_services,
    COUNT(CASE WHEN service_type = 'CONSULTATION' THEN 1 END) as consultations,
    COUNT(CASE WHEN service_type = 'PROCEDURE' THEN 1 END) as procedures,
    COUNT(CASE WHEN service_type = 'TEST' THEN 1 END) as tests,
    AVG(base_price) as avg_price
FROM service_pricing WHERE is_active = 1";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Manage Services')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .info-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;
            margin-bottom: 1.5rem;
        }
        
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            width: 200px;
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .info-value {
            flex: 1;
            color: #1e293b;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 500;
            font-size: 0.75rem;
            text-transform: uppercase;
        }
        
        .badge-consultation {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-procedure {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-test {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-medication {
            background: #fce7f3;
            color: #9f1239;
        }
        
        .badge-accommodation {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .badge-active {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-inactive {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .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;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .service-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            border-left: 4px solid #3b82f6;
        }
        
        .medical-alert {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
        
        .section-divider {
            margin: 2rem 0;
            border-top: 2px solid #e2e8f0;
        }
    </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">Manage Services</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">System Administration</li>
                                        <li class="breadcrumb-item active">Manage Services</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2">Services & Pricing Management</h3>
                                <p class="mb-0 opacity-75">Import services from CSV (Prodigy Benefits Package) or add them manually with flexible pricing options</p>
                            </div>
                            <div class="col-auto">
                                <div class="d-flex gap-2">
                                    <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addServiceModal">
                                        <i class="ri-add-line me-1"></i> Add Service
                                    </button>
                                    <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#importCSVModal">
                                        <i class="ri-upload-2-line me-1"></i> Import CSV
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alerts -->
                    <?php if ($success_message || isset($_GET['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="ri-check-line me-2"></i><?php echo $success_message ?: "Operation completed successfully!"; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_services']); ?></div>
                                <div class="stat-label">TOTAL SERVICES</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['active_services']); ?></div>
                                <div class="stat-label">ACTIVE SERVICES</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value">KES <?php echo number_format($stats['avg_price'], 0); ?></div>
                                <div class="stat-label">AVERAGE PRICE</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['procedures']); ?></div>
                                <div class="stat-label">PROCEDURES</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="info-card">
                        <h5><i class="ri-filter-3-line me-2"></i>Filter Services</h5>
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Search Services</label>
                                <input type="text" class="form-control" name="search" 
                                       placeholder="Search by service name..." 
                                       value="<?php echo htmlspecialchars($search_query); ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Service Type</label>
                                <select class="form-select" name="service_type">
                                    <option value="">All Types</option>
                                    <option value="CONSULTATION" <?php echo $service_type_filter === 'CONSULTATION' ? 'selected' : ''; ?>>Consultation</option>
                                    <option value="PROCEDURE" <?php echo $service_type_filter === 'PROCEDURE' ? 'selected' : ''; ?>>Procedure</option>
                                    <option value="TEST" <?php echo $service_type_filter === 'TEST' ? 'selected' : ''; ?>>Test/Investigation</option>
                                    <option value="MEDICATION" <?php echo $service_type_filter === 'MEDICATION' ? 'selected' : ''; ?>>Medication</option>
                                    <option value="ACCOMMODATION" <?php echo $service_type_filter === 'ACCOMMODATION' ? 'selected' : ''; ?>>Accommodation</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                    <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All</option>
                                </select>
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="ri-search-line me-1"></i>Filter
                                </button>
                                <a href="manage_services.php" class="btn btn-secondary">
                                    <i class="ri-refresh-line me-1"></i>Reset
                                </a>
                            </div>
                        </form>
                    </div>

                    <!-- Services List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <h5><i class="ri-list-check me-2"></i>Services List (<?php echo number_format($total_records); ?> services)</h5>
                                
                                <?php if ($services->num_rows > 0): ?>
                                    <?php while ($service = $services->fetch_assoc()): ?>
                                    <div class="service-card">
                                        <div class="row align-items-center">
                                            <div class="col-md-6">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($service['service_name']); ?></h6>
                                                <div class="d-flex gap-2 flex-wrap">
                                                    <span class="badge badge-<?php echo strtolower($service['service_type']); ?>">
                                                        <?php echo $service['service_type']; ?>
                                                    </span>
                                                    <span class="badge badge-<?php echo $service['is_active'] ? 'active' : 'inactive'; ?>">
                                                        <?php echo $service['is_active'] ? 'Active' : 'Inactive'; ?>
                                                    </span>
                                                    <?php if ($service['emergency_surcharge'] > 0): ?>
                                                    <span class="badge bg-warning-subtle text-warning">
                                                        Emergency: +<?php echo number_format($service['emergency_surcharge'], 0); ?>%
                                                    </span>
                                                    <?php endif; ?>
                                                    <?php if ($service['weekend_surcharge'] > 0): ?>
                                                    <span class="badge bg-info-subtle text-info">
                                                        Weekend: +<?php echo number_format($service['weekend_surcharge'], 0); ?>%
                                                    </span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="info-row">
                                                    <div class="info-label">Base Price</div>
                                                    <div class="info-value"><strong>KES <?php echo number_format($service['base_price'], 2); ?></strong></div>
                                                </div>
                                                <div class="info-row">
                                                    <div class="info-label">Insurance</div>
                                                    <div class="info-value">
                                                        <?php if ($service['insurance_price']): ?>
                                                            KES <?php echo number_format($service['insurance_price'], 2); ?>
                                                        <?php else: ?>
                                                            <span class="text-muted">Not set</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-2 text-end">
                                                <button class="btn btn-sm btn-soft-primary" onclick='editService(<?php echo json_encode($service); ?>)'>
                                                    <i class="ri-edit-line"></i>
                                                </button>
                                                <?php if ($service['is_active']): ?>
                                                <button class="btn btn-sm btn-soft-danger" onclick="confirmDelete(<?php echo $service['pricing_id']; ?>)">
                                                    <i class="ri-delete-bin-line"></i>
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>

                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                    <div class="section-divider"></div>
                                    <nav>
                                        <ul class="pagination justify-content-center">
                                            <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo ($page - 1); ?><?php echo $service_type_filter ? '&service_type=' . $service_type_filter : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?>">Previous</a>
                                            </li>
                                            <?php endif; ?>

                                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?><?php echo $service_type_filter ? '&service_type=' . $service_type_filter : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?>"><?php echo $i; ?></a>
                                            </li>
                                            <?php endfor; ?>

                                            <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo ($page + 1); ?><?php echo $service_type_filter ? '&service_type=' . $service_type_filter : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?>">Next</a>
                                            </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                    <?php endif; ?>

                                <?php else: ?>
                                    <div class="text-center py-5">
                                        <i class="ri-file-list-3-line display-4 text-muted"></i>
                                        <p class="text-muted mt-3">No services found. Add your first service or import from CSV.</p>
                                        <button class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#addServiceModal">
                                            <i class="ri-add-line me-1"></i> Add Service
                                        </button>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Service Modal -->
    <div class="modal fade" id="addServiceModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                    <h5 class="modal-title">Add New Service</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Service Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="service_name" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Service Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="service_type" required>
                                    <option value="">Select Type</option>
                                    <option value="CONSULTATION">Consultation</option>
                                    <option value="PROCEDURE">Procedure</option>
                                    <option value="TEST">Test/Investigation</option>
                                    <option value="MEDICATION">Medication</option>
                                    <option value="ACCOMMODATION">Accommodation</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Base Price (KES) <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="base_price" step="0.01" min="0" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Insurance Price (KES)</label>
                                <input type="number" class="form-control" name="insurance_price" step="0.01" min="0">
                                <small class="text-muted">Leave empty if same as base price</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Corporate Price (KES)</label>
                                <input type="number" class="form-control" name="corporate_price" step="0.01" min="0">
                                <small class="text-muted">Leave empty if same as base price</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Effective From <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="effective_from" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Emergency Surcharge (%)</label>
                                <input type="number" class="form-control" name="emergency_surcharge" step="0.01" min="0" max="100" value="0">
                                <small class="text-muted">Additional charge for emergency services</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Weekend Surcharge (%)</label>
                                <input type="number" class="form-control" name="weekend_surcharge" step="0.01" min="0" max="100" value="0">
                                <small class="text-muted">Additional charge for weekend services</small>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="add_service" class="btn btn-primary">
                            <i class="ri-add-line me-1"></i> Add Service
                        </button>
                    </div>
                </form>
            </div>
        </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" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                    <h5 class="modal-title">Edit Service</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="pricing_id" id="edit_pricing_id">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <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>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Service Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="service_type" id="edit_service_type" required>
                                    <option value="CONSULTATION">Consultation</option>
                                    <option value="PROCEDURE">Procedure</option>
                                    <option value="TEST">Test/Investigation</option>
                                    <option value="MEDICATION">Medication</option>
                                    <option value="ACCOMMODATION">Accommodation</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Base Price (KES) <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="base_price" id="edit_base_price" step="0.01" min="0" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Insurance Price (KES)</label>
                                <input type="number" class="form-control" name="insurance_price" id="edit_insurance_price" step="0.01" min="0">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Corporate Price (KES)</label>
                                <input type="number" class="form-control" name="corporate_price" id="edit_corporate_price" step="0.01" min="0">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Effective From <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="effective_from" id="edit_effective_from" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Emergency Surcharge (%)</label>
                                <input type="number" class="form-control" name="emergency_surcharge" id="edit_emergency_surcharge" step="0.01" min="0" max="100">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Weekend Surcharge (%)</label>
                                <input type="number" class="form-control" name="weekend_surcharge" id="edit_weekend_surcharge" step="0.01" min="0" max="100">
                            </div>
                            <div class="col-md-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active" value="1">
                                    <label class="form-check-label" for="edit_is_active">Active</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_service" class="btn btn-primary">
                            <i class="ri-save-line me-1"></i> Update Service
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Import CSV Modal -->
    <div class="modal fade" id="importCSVModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                    <h5 class="modal-title">Import Services from CSV</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="medical-alert mb-3">
                            <h6 class="mb-2"><i class="ri-information-line me-2"></i>CSV Format Instructions</h6>
                            <p class="mb-1"><strong>Expected Format:</strong> Prodigy Benefits Package CSV</p>
                            <p class="mb-1"><strong>Columns:</strong> ID, PROCEDURE, Treatment Group, Charges</p>
                            <p class="mb-0"><strong>Note:</strong> Duplicate services will be skipped automatically</p>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Select CSV File <span class="text-danger">*</span></label>
                            <input type="file" class="form-control" name="csv_file" accept=".csv" required>
                            <small class="text-muted">Upload your Prodigy Benefits Package CSV file</small>
                        </div>

                        <div class="info-card">
                            <h6>CSV Structure Example:</h6>
                            <pre class="mb-0" style="background: #f8fafc; padding: 1rem; border-radius: 6px; font-size: 0.875rem;">
ID,PROCEDURE,Treatment Group,Charges
1,First Consultation,Consultation,"4,000.00"
2,Aural Toilet,Treatment,"3,000.00"
3,Audiometry,Investigation,"2,500.00"</pre>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="import_csv" class="btn btn-primary">
                            <i class="ri-upload-2-line me-1"></i> Import Services
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        function editService(service) {
            document.getElementById('edit_pricing_id').value = service.pricing_id;
            document.getElementById('edit_service_name').value = service.service_name;
            document.getElementById('edit_service_type').value = service.service_type;
            document.getElementById('edit_base_price').value = service.base_price;
            document.getElementById('edit_insurance_price').value = service.insurance_price || '';
            document.getElementById('edit_corporate_price').value = service.corporate_price || '';
            document.getElementById('edit_effective_from').value = service.effective_from;
            document.getElementById('edit_emergency_surcharge').value = service.emergency_surcharge;
            document.getElementById('edit_weekend_surcharge').value = service.weekend_surcharge;
            document.getElementById('edit_is_active').checked = service.is_active == 1;
            
            var editModal = new bootstrap.Modal(document.getElementById('editServiceModal'));
            editModal.show();
        }

        function confirmDelete(pricingId) {
            Swal.fire({
                title: 'Deactivate Service?',
                text: "This will deactivate the service. You can reactivate it later.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, deactivate it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'manage_services.php?delete=' + pricingId;
                }
            });
        }
    </script>
</body>
</html>