<?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
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_charge':
                $charge_code = strtoupper($_POST['charge_code']);
                $charge_name = $_POST['charge_name'];
                $charge_type = $_POST['charge_type'];
                $default_amount = $_POST['default_amount'];
                $is_taxable = isset($_POST['is_taxable']) ? 1 : 0;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Check if charge code already exists
                $check_sql = "SELECT charge_id FROM charge_types WHERE charge_code = ?";
                $check_stmt = $conn->prepare($check_sql);
                $check_stmt->bind_param("s", $charge_code);
                $check_stmt->execute();
                
                if ($check_stmt->get_result()->num_rows > 0) {
                    echo json_encode(['success' => false, 'message' => 'Charge code already exists']);
                } else {
                    $sql = "INSERT INTO charge_types (charge_code, charge_name, charge_type, default_amount, is_taxable, is_active) 
                            VALUES (?, ?, ?, ?, ?, ?)";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("sssdii", $charge_code, $charge_name, $charge_type, $default_amount, $is_taxable, $is_active);
                    
                    if ($stmt->execute()) {
                        echo json_encode(['success' => true, 'message' => 'Charge type added successfully']);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Failed to add charge type']);
                    }
                }
                exit();
                break;
                
            case 'update_charge':
                $charge_id = $_POST['charge_id'];
                $charge_name = $_POST['charge_name'];
                $charge_type = $_POST['charge_type'];
                $default_amount = $_POST['default_amount'];
                $is_taxable = isset($_POST['is_taxable']) ? 1 : 0;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                $sql = "UPDATE charge_types SET charge_name = ?, charge_type = ?, default_amount = ?, is_taxable = ?, is_active = ? 
                        WHERE charge_id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ssdiii", $charge_name, $charge_type, $default_amount, $is_taxable, $is_active, $charge_id);
                
                if ($stmt->execute()) {
                    echo json_encode(['success' => true, 'message' => 'Charge type updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update charge type']);
                }
                exit();
                break;
                
            case 'delete_charge':
                $charge_id = $_POST['charge_id'];
                
                // Check if charge is being used
                $usage_check = "SELECT COUNT(*) as count FROM shipments WHERE 
                               (fuel_surcharge > 0 AND ? = 1) OR 
                               (insurance_charges > 0 AND ? = 2) OR 
                               (handling_charges > 0 AND ? = 3) OR 
                               (customs_charges > 0 AND ? = 6) OR 
                               (other_charges > 0 AND ? IN (4,5,7,8,9,10))";
                $usage_stmt = $conn->prepare($usage_check);
                $usage_stmt->bind_param("iiiii", $charge_id, $charge_id, $charge_id, $charge_id, $charge_id);
                $usage_stmt->execute();
                $usage_result = $usage_stmt->get_result()->fetch_assoc();
                
                if ($usage_result['count'] > 0) {
                    echo json_encode(['success' => false, 'message' => 'Cannot delete charge type. It is being used in shipments.']);
                } else {
                    $sql = "DELETE FROM charge_types WHERE charge_id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("i", $charge_id);
                    
                    if ($stmt->execute()) {
                        echo json_encode(['success' => true, 'message' => 'Charge type deleted successfully']);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Failed to delete charge type']);
                    }
                }
                exit();
                break;
        }
    }
}

// Fetch all charge types
$sql_charges = "SELECT * FROM charge_types ORDER BY charge_code";
$charges_result = $conn->query($sql_charges);

// Get charge usage statistics
$sql_stats = "SELECT 
    ct.charge_code,
    ct.charge_name,
    CASE 
        WHEN ct.charge_code = 'FUEL' THEN (SELECT COUNT(*) FROM shipments WHERE fuel_surcharge > 0)
        WHEN ct.charge_code = 'INSUR' THEN (SELECT COUNT(*) FROM shipments WHERE insurance_charges > 0)
        WHEN ct.charge_code = 'HANDLE' THEN (SELECT COUNT(*) FROM shipments WHERE handling_charges > 0)
        WHEN ct.charge_code = 'CUSTOMS' THEN (SELECT COUNT(*) FROM shipments WHERE customs_charges > 0)
        WHEN ct.charge_code IN ('PICKUP', 'DELIVER', 'STORAGE', 'OVERSIZE', 'SECURITY', 'DOCUMENT') 
        THEN (SELECT COUNT(*) FROM shipments WHERE other_charges > 0)
        ELSE 0
    END as usage_count,
    CASE 
        WHEN ct.charge_code = 'FUEL' THEN (SELECT COALESCE(SUM(fuel_surcharge), 0) FROM shipments WHERE fuel_surcharge > 0)
        WHEN ct.charge_code = 'INSUR' THEN (SELECT COALESCE(SUM(insurance_charges), 0) FROM shipments WHERE insurance_charges > 0)
        WHEN ct.charge_code = 'HANDLE' THEN (SELECT COALESCE(SUM(handling_charges), 0) FROM shipments WHERE handling_charges > 0)
        WHEN ct.charge_code = 'CUSTOMS' THEN (SELECT COALESCE(SUM(customs_charges), 0) FROM shipments WHERE customs_charges > 0)
        WHEN ct.charge_code IN ('PICKUP', 'DELIVER', 'STORAGE', 'OVERSIZE', 'SECURITY', 'DOCUMENT') 
        THEN (SELECT COALESCE(SUM(other_charges), 0) FROM shipments WHERE other_charges > 0)
        ELSE 0
    END as total_amount
FROM charge_types ct
ORDER BY usage_count DESC";

$stats_result = $conn->query($sql_stats);
$charge_stats = [];
while ($row = $stats_result->fetch_assoc()) {
    $charge_stats[$row['charge_code']] = $row;
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Charge Configuration - Freight Management System')); ?>
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.min.css" rel="stylesheet">
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .charge-config-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-left: 4px solid #3b82f6;
            transition: all 0.3s ease;
        }
        .stats-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        .charge-type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        .type-fixed { background: #dbeafe; color: #1e40af; }
        .type-percentage { background: #d1fae5; color: #065f46; }
        .type-weight_based { background: #fef3c7; color: #92400e; }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .status-active { background: #d1fae5; color: #065f46; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
    </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"><i class="ri-settings-3-line me-2"></i>Charge 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="#">Financial</a></li>
                                        <li class="breadcrumb-item active">Charge Configuration</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charge Statistics -->
                    <div class="row">
                        <?php 
                        $total_charges = count($charge_stats);
                        $active_charges = 0;
                        $total_usage = 0;
                        $total_revenue = 0;
                        
                        $charges_result->data_seek(0);
                        while ($charge = $charges_result->fetch_assoc()) {
                            if ($charge['is_active']) $active_charges++;
                        }
                        
                        foreach ($charge_stats as $stat) {
                            $total_usage += $stat['usage_count'];
                            $total_revenue += $stat['total_amount'];
                        }
                        ?>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="ri-bar-chart-2-line fs-4 text-success me-2"></i>
                                    <h6 class="mb-0">Total Usage</h6>
                                </div>
                                <div class="d-flex align-items-end">
                                    <div>
                                        <h4 class="mb-1"><?php echo number_format($total_usage); ?></h4>
                                        <p class="text-muted mb-0">Applications</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="ri-money-dollar-circle-line fs-4 text-warning me-2"></i>
                                    <h6 class="mb-0">Total Revenue</h6>
                                </div>
                                <div class="d-flex align-items-end">
                                    <div>
                                        <h4 class="mb-1">KSh <?php echo number_format($total_revenue); ?></h4>
                                        <p class="text-muted mb-0">From charges</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="ri-settings-4-line fs-4 text-info me-2"></i>
                                    <h6 class="mb-0">Configuration</h6>
                                </div>
                                <div class="d-flex align-items-end">
                                    <div>
                                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addChargeModal">
                                            <i class="ri-add-line me-1"></i>Add New Charge
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charge Types Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="charge-config-card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center justify-content-between">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-price-tag-3-line me-2"></i>Charge Types Configuration
                                        </h5>
                                        <div class="d-flex gap-2">
                                            <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addChargeModal">
                                                <i class="ri-add-line me-1"></i>Add Charge Type
                                            </button>
                                            <button class="btn btn-outline-primary btn-sm" onclick="exportCharges()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="charges-table" class="table table-striped dt-responsive nowrap">
                                            <thead>
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Charge Name</th>
                                                    <th>Type</th>
                                                    <th>Default Amount</th>
                                                    <th>Taxable</th>
                                                    <th>Usage</th>
                                                    <th>Total Revenue</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $charges_result->data_seek(0);
                                                while ($charge = $charges_result->fetch_assoc()): 
                                                    $stats = $charge_stats[$charge['charge_code']] ?? ['usage_count' => 0, 'total_amount' => 0];
                                                ?>
                                                <tr>
                                                    <td>
                                                        <span class="fw-semibold text-primary"><?php echo $charge['charge_code']; ?></span>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <div class="fw-semibold"><?php echo htmlspecialchars($charge['charge_name']); ?></div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="charge-type-badge type-<?php echo strtolower($charge['charge_type']); ?>">
                                                            <?php echo str_replace('_', ' ', $charge['charge_type']); ?>
                                                        </span>
                                                    </td>
                                                    <td class="fw-semibold">
                                                        <?php if ($charge['charge_type'] == 'PERCENTAGE'): ?>
                                                            <?php echo $charge['default_amount']; ?>%
                                                        <?php else: ?>
                                                            KSh <?php echo number_format($charge['default_amount'], 2); ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($charge['is_taxable']): ?>
                                                            <i class="ri-check-line text-success fs-5"></i>
                                                        <?php else: ?>
                                                            <i class="ri-close-line text-danger fs-5"></i>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-info"><?php echo number_format($stats['usage_count']); ?> times</span>
                                                    </td>
                                                    <td class="fw-semibold text-success">
                                                        KSh <?php echo number_format($stats['total_amount'], 2); ?>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo $charge['is_active'] ? 'active' : 'inactive'; ?>">
                                                            <?php echo $charge['is_active'] ? 'Active' : 'Inactive'; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="dropdown">
                                                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                                                                <i class="ri-more-2-line"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li><a class="dropdown-item" href="#" onclick="editCharge(<?php echo htmlspecialchars(json_encode($charge)); ?>)">
                                                                    <i class="ri-edit-line me-2"></i>Edit
                                                                </a></li>
                                                                <li><a class="dropdown-item" href="#" onclick="viewChargeUsage('<?php echo $charge['charge_code']; ?>')">
                                                                    <i class="ri-bar-chart-line me-2"></i>View Usage
                                                                </a></li>
                                                                <li><hr class="dropdown-divider"></li>
                                                                <?php if ($stats['usage_count'] == 0): ?>
                                                                <li><a class="dropdown-item text-danger" href="#" onclick="deleteCharge(<?php echo $charge['charge_id']; ?>)">
                                                                    <i class="ri-delete-bin-line me-2"></i>Delete
                                                                </a></li>
                                                                <?php else: ?>
                                                                <li><a class="dropdown-item text-muted disabled">
                                                                    <i class="ri-delete-bin-line me-2"></i>Cannot Delete (In Use)
                                                                </a></li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charge Type Descriptions -->
                    <div class="row">
                        <div class="col-12">
                            <div class="charge-config-card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-information-line me-2"></i>Charge Type Descriptions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="p-3 border rounded">
                                                <h6 class="text-primary"><i class="ri-price-tag-line me-2"></i>Fixed Amount</h6>
                                                <p class="mb-0">A fixed amount charged regardless of shipment value or weight. Example: Handling fee of KSh 500.</p>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="p-3 border rounded">
                                                <h6 class="text-success"><i class="ri-percent-line me-2"></i>Percentage Based</h6>
                                                <p class="mb-0">A percentage of the shipment value or base freight charge. Example: 15% fuel surcharge.</p>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="p-3 border rounded">
                                                <h6 class="text-warning"><i class="ri-scales-line me-2"></i>Weight Based</h6>
                                                <p class="mb-0">Charged per unit weight (kg). Example: KSh 50 per kg for storage.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Charge Modal -->
    <div class="modal fade" id="addChargeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-add-line me-2"></i>Add New Charge Type
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="addChargeForm">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Charge Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="charge_code" required maxlength="10" style="text-transform: uppercase;">
                                <div class="form-text">Unique code (e.g., FUEL, INSUR)</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Charge Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="charge_name" required maxlength="100">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Charge Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="charge_type" required>
                                    <option value="">Select Type</option>
                                    <option value="FIXED">Fixed Amount</option>
                                    <option value="PERCENTAGE">Percentage</option>
                                    <option value="WEIGHT_BASED">Weight Based</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Default Amount <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="default_amount" step="0.01" min="0" required>
                                <div class="form-text" id="amount-help">Enter default amount</div>
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_taxable" id="is_taxable" checked>
                                    <label class="form-check-label" for="is_taxable">
                                        Subject to Tax (VAT)
                                    </label>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="is_active" checked>
                                    <label class="form-check-label" for="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" class="btn btn-primary">
                            <i class="ri-save-line me-1"></i>Add Charge Type
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Charge Modal -->
    <div class="modal fade" id="editChargeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-edit-line me-2"></i>Edit Charge Type
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="editChargeForm">
                    <div class="modal-body">
                        <input type="hidden" name="charge_id" id="edit_charge_id">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Charge Code</label>
                                <input type="text" class="form-control" id="edit_charge_code" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Charge Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="charge_name" id="edit_charge_name" required maxlength="100">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Charge Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="charge_type" id="edit_charge_type" required>
                                    <option value="FIXED">Fixed Amount</option>
                                    <option value="PERCENTAGE">Percentage</option>
                                    <option value="WEIGHT_BASED">Weight Based</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Default Amount <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="default_amount" id="edit_default_amount" step="0.01" min="0" required>
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_taxable" id="edit_is_taxable">
                                    <label class="form-check-label" for="edit_is_taxable">
                                        Subject to Tax (VAT)
                                    </label>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                                    <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" class="btn btn-primary">
                            <i class="ri-save-line me-1"></i>Update Charge Type
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.all.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize DataTable
        $('#charges-table').DataTable({
            responsive: true,
            pageLength: 25,
            order: [[0, 'asc']],
            columnDefs: [
                { orderable: false, targets: -1 }
            ]
        });

        // Update amount help text based on charge type
        $('select[name="charge_type"]').on('change', function() {
            const type = $(this).val();
            let helpText = 'Enter default amount';
            
            if (type === 'PERCENTAGE') {
                helpText = 'Enter percentage (e.g., 15 for 15%)';
            } else if (type === 'WEIGHT_BASED') {
                helpText = 'Enter amount per KG';
            } else if (type === 'FIXED') {
                helpText = 'Enter fixed amount in KSh';
            }
            
            $('#amount-help').text(helpText);
        });

        // Handle add form submission
        $('#addChargeForm').on('submit', function(e) {
            e.preventDefault();
            addCharge();
        });

        // Handle edit form submission
        $('#editChargeForm').on('submit', function(e) {
            e.preventDefault();
            updateCharge();
        });
    });

    function addCharge() {
        const formData = new FormData($('#addChargeForm')[0]);
        formData.append('action', 'add_charge');
        
        $.ajax({
            url: '',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                const result = JSON.parse(response);
                if (result.success) {
                    Swal.fire('Success!', result.message, 'success').then(() => {
                        $('#addChargeModal').modal('hide');
                        location.reload();
                    });
                } else {
                    Swal.fire('Error!', result.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error!', 'Something went wrong. Please try again.', 'error');
            }
        });
    }

    function editCharge(charge) {
        $('#edit_charge_id').val(charge.charge_id);
        $('#edit_charge_code').val(charge.charge_code);
        $('#edit_charge_name').val(charge.charge_name);
        $('#edit_charge_type').val(charge.charge_type);
        $('#edit_default_amount').val(charge.default_amount);
        $('#edit_is_taxable').prop('checked', charge.is_taxable == 1);
        $('#edit_is_active').prop('checked', charge.is_active == 1);
        
        $('#editChargeModal').modal('show');
    }

    function updateCharge() {
        const formData = new FormData($('#editChargeForm')[0]);
        formData.append('action', 'update_charge');
        
        $.ajax({
            url: '',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                const result = JSON.parse(response);
                if (result.success) {
                    Swal.fire('Success!', result.message, 'success').then(() => {
                        $('#editChargeModal').modal('hide');
                        location.reload();
                    });
                } else {
                    Swal.fire('Error!', result.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error!', 'Something went wrong. Please try again.', 'error');
            }
        });
    }

    function deleteCharge(chargeId) {
        Swal.fire({
            title: 'Delete Charge Type',
            text: 'Are you sure you want to delete this charge type? This action cannot be undone.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Delete',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '',
                    method: 'POST',
                    data: {
                        action: 'delete_charge',
                        charge_id: chargeId
                    },
                    success: function(response) {
                        const result = JSON.parse(response);
                        if (result.success) {
                            Swal.fire('Deleted!', result.message, 'success').then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error!', result.message, 'error');
                        }
                    }
                });
            }
        });
    }

    function viewChargeUsage(chargeCode) {
        // This would open a modal or navigate to a detailed usage report
        Swal.fire({
            title: 'Charge Usage Details',
            text: `Detailed usage analytics for ${chargeCode} will be implemented here.`,
            icon: 'info'
        });
    }

    function exportCharges() {
        Swal.fire({
            title: 'Export Charges',
            text: 'Please wait while we prepare your file...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        setTimeout(() => {
            Swal.fire('Success!', 'Charge configuration exported successfully.', 'success');
        }, 2000);
    }
    </script>

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