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

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_rate':
                $rate_name = trim($_POST['rate_name']);
                $service_id = intval($_POST['service_id']);
                $origin_zone_id = intval($_POST['origin_zone_id']);
                $destination_zone_id = intval($_POST['destination_zone_id']);
                $weight_from = floatval($_POST['weight_from']);
                $weight_to = floatval($_POST['weight_to']);
                $rate_per_kg = floatval($_POST['rate_per_kg']);
                $minimum_charge = floatval($_POST['minimum_charge']);
                $fuel_surcharge_percent = floatval($_POST['fuel_surcharge_percent']);
                $effective_date = $_POST['effective_date'];
                $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
                $customer_id = !empty($_POST['customer_id']) ? intval($_POST['customer_id']) : null;
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                if ($weight_from >= $weight_to) {
                    $message = "Weight 'from' must be less than weight 'to'!";
                    $message_type = "danger";
                    break;
                }

                // Check for overlapping rates
                $overlap_sql = "SELECT rate_id FROM rate_cards WHERE 
                               service_id = ? AND origin_zone_id = ? AND destination_zone_id = ? 
                               AND ((weight_from <= ? AND weight_to > ?) OR (weight_from < ? AND weight_to >= ?))
                               AND (customer_id = ? OR (customer_id IS NULL AND ? IS NULL))
                               AND effective_date <= ? AND (expiry_date IS NULL OR expiry_date >= ?)
                               AND is_active = 1";
                
                $overlap_stmt = $conn->prepare($overlap_sql);
                $overlap_stmt->bind_param("iiiidddiiiss", 
                    $service_id, $origin_zone_id, $destination_zone_id,
                    $weight_from, $weight_from, $weight_to, $weight_to,
                    $customer_id, $customer_id, $effective_date, $effective_date
                );
                $overlap_stmt->execute();
                
                if ($overlap_stmt->get_result()->num_rows > 0) {
                    $message = "A rate already exists for this service, route, and weight range!";
                    $message_type = "warning";
                } else {
                    $insert_sql = "INSERT INTO rate_cards (rate_name, service_id, origin_zone_id, destination_zone_id, 
                                   weight_from, weight_to, rate_per_kg, minimum_charge, fuel_surcharge_percent, 
                                   effective_date, expiry_date, customer_id, is_active, created_by) 
                                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $insert_stmt = $conn->prepare($insert_sql);
                    $insert_stmt->bind_param("siiiididssiii", 
                        $rate_name, $service_id, $origin_zone_id, $destination_zone_id,
                        $weight_from, $weight_to, $rate_per_kg, $minimum_charge, $fuel_surcharge_percent,
                        $effective_date, $expiry_date, $customer_id, $is_active, $user_id
                    );
                    
                    if ($insert_stmt->execute()) {
                        $message = "Rate card added successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error adding rate card: " . $conn->error;
                        $message_type = "danger";
                    }
                }
                break;

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

            case 'delete_rate':
                $rate_id = intval($_POST['rate_id']);
                
                $delete_sql = "DELETE FROM rate_cards WHERE rate_id = ?";
                $delete_stmt = $conn->prepare($delete_sql);
                $delete_stmt->bind_param("i", $rate_id);
                
                if ($delete_stmt->execute()) {
                    echo json_encode(['success' => true]);
                    exit;
                } else {
                    echo json_encode(['success' => false, 'error' => $conn->error]);
                    exit;
                }
                break;
        }
    }
}

// Get filters
$service_filter = $_GET['service'] ?? '';
$zone_filter = $_GET['zone'] ?? '';
$customer_filter = $_GET['customer'] ?? '';
$status_filter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

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

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

if (!empty($service_filter)) {
    $where_conditions[] = "rc.service_id = ?";
    $params[] = $service_filter;
    $param_types .= 'i';
}

if (!empty($zone_filter)) {
    $where_conditions[] = "(rc.origin_zone_id = ? OR rc.destination_zone_id = ?)";
    $params[] = $zone_filter;
    $params[] = $zone_filter;
    $param_types .= 'ii';
}

if (!empty($search)) {
    $where_conditions[] = "(rc.rate_name LIKE ? OR st.service_name LIKE ?)";
    $search_param = '%' . $search . '%';
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'ss';
}

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

// Get rate cards with details
$rates_sql = "SELECT 
    rc.*,
    st.service_name,
    st.service_code,
    oz.zone_name as origin_zone_name,
    dz.zone_name as destination_zone_name,
    CASE 
        WHEN c.customer_type = 'CORPORATE' THEN c.company_name
        ELSE CONCAT(c.first_name, ' ', c.last_name)
    END as customer_name,
    creator.full_name as created_by_name,
    CASE 
        WHEN rc.is_active = 0 THEN 'INACTIVE'
        WHEN rc.effective_date > CURDATE() THEN 'FUTURE'
        WHEN rc.expiry_date IS NOT NULL AND rc.expiry_date < CURDATE() THEN 'EXPIRED'
        ELSE 'ACTIVE'
    END as rate_status
FROM rate_cards rc
INNER JOIN service_types st ON rc.service_id = st.service_id
INNER JOIN zones oz ON rc.origin_zone_id = oz.zone_id
INNER JOIN zones dz ON rc.destination_zone_id = dz.zone_id
LEFT JOIN customers c ON rc.customer_id = c.customer_id
LEFT JOIN users creator ON rc.created_by = creator.user_id
$where_clause
ORDER BY rc.effective_date DESC
LIMIT $offset, $records_per_page";

if (!empty($params)) {
    $rates_stmt = $conn->prepare($rates_sql);
    $rates_stmt->bind_param($param_types, ...$params);
    $rates_stmt->execute();
    $rates_result = $rates_stmt->get_result();
} else {
    $rates_result = $conn->query($rates_sql);
}

// Get dropdown data
$services_sql = "SELECT service_id, service_code, service_name FROM service_types WHERE is_active = 1 ORDER BY service_name";
$services_result = $conn->query($services_sql);

$zones_sql = "SELECT zone_id, zone_code, zone_name FROM zones WHERE is_active = 1 ORDER BY zone_name";
$zones_result = $conn->query($zones_sql);

$customers_sql = "SELECT customer_id, customer_code, 
                  CASE 
                      WHEN customer_type = 'CORPORATE' THEN company_name
                      ELSE CONCAT(first_name, ' ', last_name)
                  END as customer_name
                  FROM customers WHERE status = 'ACTIVE' ORDER BY customer_name LIMIT 100";
$customers_result = $conn->query($customers_sql);

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_rates,
    COUNT(CASE WHEN is_active = 1 AND effective_date <= CURDATE() AND (expiry_date IS NULL OR expiry_date >= CURDATE()) THEN 1 END) as active_rates,
    COUNT(CASE WHEN is_active = 0 THEN 1 END) as inactive_rates,
    COUNT(CASE WHEN expiry_date < CURDATE() THEN 1 END) as expired_rates
FROM rate_cards";
$stats_result = $conn->query($stats_sql);
$rate_stats = $stats_result->fetch_assoc();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Rate Card Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .rate-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            margin-bottom: 1rem;
            transition: all 0.2s ease;
        }
        
        .rate-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .rate-header {
            padding: 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        }
        
        .rate-body {
            padding: 1.5rem;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .status-expired { background: #fef3c7; color: #d97706; }
        .status-future { background: #dbeafe; color: #1d4ed8; }
        
        .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;
        }
        
        .filters-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .form-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
    </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">Rate Card Management</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 active">Rate Cards</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 -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value" style="color: #3b82f6;"><?php echo number_format($rate_stats['total_rates']); ?></div>
                            <div class="stat-label">Total Rates</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #10b981;"><?php echo number_format($rate_stats['active_rates']); ?></div>
                            <div class="stat-label">Active Rates</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #f59e0b;"><?php echo number_format($rate_stats['expired_rates']); ?></div>
                            <div class="stat-label">Expired Rates</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #ef4444;"><?php echo number_format($rate_stats['inactive_rates']); ?></div>
                            <div class="stat-label">Inactive Rates</div>
                        </div>
                    </div>

                    <!-- Add Rate Form -->
                    <div class="form-section" id="addRateForm" style="display: none;">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5>Add New Rate Card</h5>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="hideAddForm()">Cancel</button>
                        </div>
                        
                        <form method="POST">
                            <input type="hidden" name="action" value="add_rate">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Rate Name *</label>
                                        <input type="text" class="form-control" name="rate_name" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Service *</label>
                                        <select class="form-select" name="service_id" required>
                                            <option value="">Select Service</option>
                                            <?php while($service = $services_result->fetch_assoc()): ?>
                                            <option value="<?php echo $service['service_id']; ?>">
                                                <?php echo $service['service_name']; ?> (<?php echo $service['service_code']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Origin Zone *</label>
                                        <select class="form-select" name="origin_zone_id" required>
                                            <option value="">Select Origin</option>
                                            <?php while($zone = $zones_result->fetch_assoc()): ?>
                                            <option value="<?php echo $zone['zone_id']; ?>">
                                                <?php echo $zone['zone_name']; ?> (<?php echo $zone['zone_code']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Destination Zone *</label>
                                        <select class="form-select" name="destination_zone_id" required>
                                            <option value="">Select Destination</option>
                                            <?php 
                                            $zones_result->data_seek(0);
                                            while($zone = $zones_result->fetch_assoc()): 
                                            ?>
                                            <option value="<?php echo $zone['zone_id']; ?>">
                                                <?php echo $zone['zone_name']; ?> (<?php echo $zone['zone_code']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Weight From (KG) *</label>
                                        <input type="number" class="form-control" name="weight_from" step="0.01" min="0" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Weight To (KG) *</label>
                                        <input type="number" class="form-control" name="weight_to" step="0.01" min="0.01" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Rate per KG *</label>
                                        <input type="number" class="form-control" name="rate_per_kg" step="0.01" min="0" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Minimum Charge</label>
                                        <input type="number" class="form-control" name="minimum_charge" step="0.01" min="0" value="0">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Fuel Surcharge (%)</label>
                                        <input type="number" class="form-control" name="fuel_surcharge_percent" step="0.01" min="0" value="0">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Effective Date *</label>
                                        <input type="date" class="form-control" name="effective_date" required value="<?php echo date('Y-m-d'); ?>">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Expiry Date</label>
                                        <input type="date" class="form-control" name="expiry_date">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label class="form-label">Customer (Optional)</label>
                                        <select class="form-select" name="customer_id">
                                            <option value="">General Rate</option>
                                            <?php while($customer = $customers_result->fetch_assoc()): ?>
                                            <option value="<?php echo $customer['customer_id']; ?>">
                                                <?php echo $customer['customer_name']; ?> (<?php echo $customer['customer_code']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="is_active" checked>
                                        <label class="form-check-label">Active</label>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-end gap-2 mt-3">
                                <button type="button" class="btn btn-outline-secondary" onclick="hideAddForm()">Cancel</button>
                                <button type="submit" class="btn btn-primary">Add Rate Card</button>
                            </div>
                        </form>
                    </div>

                    <!-- Filters -->
                    <div class="filters-section">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5>Rate Card Management</h5>
                            <button type="button" class="btn btn-primary" onclick="showAddForm()">
                                <i class="bx bx-plus"></i> Add New Rate
                            </button>
                        </div>
                        
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search rates...">
                            </div>
                            <div class="col-md-2">
                                <select class="form-select" name="service">
                                    <option value="">All Services</option>
                                    <?php 
                                    $services_result->data_seek(0);
                                    while($service = $services_result->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $service['service_id']; ?>" <?php echo $service_filter == $service['service_id'] ? 'selected' : ''; ?>>
                                        <?php echo $service['service_name']; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select class="form-select" name="zone">
                                    <option value="">All Zones</option>
                                    <?php 
                                    $zones_result->data_seek(0);
                                    while($zone = $zones_result->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $zone['zone_id']; ?>" <?php echo $zone_filter == $zone['zone_id'] ? 'selected' : ''; ?>>
                                        <?php echo $zone['zone_name']; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <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>
                                    <option value="expired" <?php echo $status_filter === 'expired' ? 'selected' : ''; ?>>Expired</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-outline-primary w-100">Filter</button>
                            </div>
                        </form>
                    </div>

                    <!-- Rate Cards List -->
                    <div class="row">
                        <?php if ($rates_result->num_rows > 0): ?>
                            <?php while($rate = $rates_result->fetch_assoc()): ?>
                            <div class="col-md-6 col-xl-4">
                                <div class="rate-card">
                                    <div class="rate-header">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6><?php echo htmlspecialchars($rate['rate_name']); ?></h6>
                                                <small><?php echo $rate['service_name']; ?></small>
                                            </div>
                                            <span class="status-badge status-<?php echo strtolower($rate['rate_status']); ?>">
                                                <?php echo $rate['rate_status']; ?>
                                            </span>
                                        </div>
                                    </div>
                                    
                                    <div class="rate-body">
                                        <div class="mb-2">
                                            <strong><?php echo $rate['origin_zone_name']; ?> → <?php echo $rate['destination_zone_name']; ?></strong>
                                        </div>
                                        
                                        <div class="mb-2">
                                            <small class="text-muted">Weight Range:</small>
                                            <span class="fw-bold"><?php echo $rate['weight_from']; ?> - <?php echo $rate['weight_to']; ?> KG</span>
                                        </div>
                                        
                                        <div class="mb-2">
                                            <small class="text-muted">Rate:</small>
                                            <span class="fw-bold">KES <?php echo number_format($rate['rate_per_kg'], 2); ?>/KG</span>
                                        </div>
                                        
                                        <?php if ($rate['minimum_charge'] > 0): ?>
                                        <div class="mb-2">
                                            <small class="text-muted">Min Charge:</small>
                                            <span>KES <?php echo number_format($rate['minimum_charge'], 2); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="mb-3">
                                            <small class="text-muted">Effective:</small>
                                            <span><?php echo date('M j, Y', strtotime($rate['effective_date'])); ?></span>
                                            <?php if ($rate['expiry_date']): ?>
                                            - <?php echo date('M j, Y', strtotime($rate['expiry_date'])); ?>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <?php if ($rate['customer_name']): ?>
                                        <div class="mb-3">
                                            <span class="badge bg-warning"><?php echo htmlspecialchars($rate['customer_name']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="d-flex gap-1">
                                            <button class="btn btn-outline-primary btn-sm" onclick="editRate(<?php echo $rate['rate_id']; ?>)">
                                                <i class="bx bx-edit"></i>
                                            </button>
                                            <button class="btn btn-outline-secondary btn-sm" onclick="duplicateRate(<?php echo $rate['rate_id']; ?>)">
                                                <i class="bx bx-copy"></i>
                                            </button>
                                            <button class="btn btn-outline-danger btn-sm" onclick="deleteRate(<?php echo $rate['rate_id']; ?>, '<?php echo htmlspecialchars($rate['rate_name']); ?>')">
                                                <i class="bx bx-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12 text-center py-5">
                                <h5 class="text-muted">No rate cards found</h5>
                                <p>Start by creating your first rate card.</p>
                                <button class="btn btn-primary" onclick="showAddForm()">Add Rate Card</button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        function showAddForm() {
            document.getElementById('addRateForm').style.display = 'block';
            document.querySelector('input[name="rate_name"]').focus();
        }
        
        function hideAddForm() {
            document.getElementById('addRateForm').style.display = 'none';
            document.querySelector('#addRateForm form').reset();
        }
        
        function editRate(rateId) {
            // This would typically open a modal or redirect to edit page
            window.location.href = `edit_rate.php?id=${rateId}`;
        }
        
        function duplicateRate(rateId) {
            if (confirm('Create a copy of this rate card?')) {
                fetch('duplicate_rate.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `rate_id=${rateId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Rate card duplicated successfully!');
                        location.reload();
                    } else {
                        alert('Error: ' + data.error);
                    }
                });
            }
        }
        
        function deleteRate(rateId, rateName) {
            if (confirm(`Are you sure you want to delete "${rateName}"?`)) {
                fetch('rate_card_management.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=delete_rate&rate_id=${rateId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + data.error);
                    }
                });
            }
        }
        
        // Weight validation
        document.addEventListener('DOMContentLoaded', function() {
            const weightFrom = document.querySelector('input[name="weight_from"]');
            const weightTo = document.querySelector('input[name="weight_to"]');
            
            if (weightFrom && weightTo) {
                weightFrom.addEventListener('change', validateWeights);
                weightTo.addEventListener('change', validateWeights);
            }
            
            function validateWeights() {
                const from = parseFloat(weightFrom.value);
                const to = parseFloat(weightTo.value);
                
                if (from >= to) {
                    weightTo.setCustomValidity('Weight "to" must be greater than weight "from"');
                } else {
                    weightTo.setCustomValidity('');
                }
            }
        });
    </script>

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