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

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

// Check for required file_number parameter
if (!isset($_GET['file_number']) || empty($_GET['file_number'])) {
    $_SESSION['error_message'] = "No file number provided";
    header('Location: file_list.php');
    exit();
}

$file_number = $_GET['file_number'];

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
} else {
    // Handle case if user details not found
    $_SESSION['error_message'] = "User details not found";
    header('Location: login.php');
    exit();
}

// Check permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    return isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id]);
}

// Check if user has edit permission
if (!hasPermission($role_id, 'edit')) {
    $_SESSION['error_message'] = "You don't have permission to edit pre-proforma data";
    header('Location: view_file.php?id=' . $file_id);
    exit();
}

// Get file details
$file_query = "SELECT f.*, c.first_name, c.last_name 
              FROM files f 
              LEFT JOIN customers c ON f.customer = c.customer_id 
              WHERE f.file_number = ?";
$file_stmt = $conn->prepare($file_query);
$file_stmt->bind_param('s', $file_number);
$file_stmt->execute();
$file_result = $file_stmt->get_result();

if ($file_result->num_rows === 0) {
    $_SESSION['error_message'] = "File not found";
    header('Location: file_list.php');
    exit();
}

$file = $file_result->fetch_assoc();
$file_id = $file['id'];

// Fetch pre-proforma data
$query = "SELECT * FROM pre_proforma WHERE file_number = ? ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $file_number);
$stmt->execute();
$result = $stmt->get_result();

$charges = [];
$all_in_data = null;
$operational_data = null;
$non_operational_data = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        if ($row['all_in'] == 'Yes') {
            $all_in_data = $row;
        } elseif ($row['category'] == 'Operational') {
            $operational_data = $row;
        } elseif ($row['category'] == 'Non-Operational') {
            $non_operational_data[] = $row;
        }
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Freight Management System";
}

// Check if proforma already exists
$proforma_query = "SELECT COUNT(*) as count FROM proforma WHERE file_number = ?";
$proforma_stmt = $conn->prepare($proforma_query);
$proforma_stmt->bind_param('s', $file_number);
$proforma_stmt->execute();
$proforma_result = $proforma_stmt->get_result();
$proforma_exists = ($proforma_result->fetch_assoc()['count'] > 0);

if ($proforma_exists) {
    $_SESSION['error_message'] = "Cannot edit pre-proforma as proforma already exists";
    header('Location: view_file.php?id=' . $file_id);
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $conn->begin_transaction();
        
        // Delete existing pre_proforma records for this file
        $delete_query = "DELETE FROM pre_proforma WHERE file_number = ?";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bind_param('s', $file_number);
        $delete_stmt->execute();
        
        // Get submitted data
        $all_in = $_POST['allin'] ?? 'No';
        $all_in_amount = ($all_in === 'Yes') ? floatval($_POST['all_in_amount']) : null;
        $currency = $_POST['currency'] ?? '$';
        
        // Insert agency fee (operational cost)
        $agency_fees = floatval($_POST['agency_fees'] ?? 0);
        $vatable = $_POST['vatable'] ?? 'No';
        $vat_amount = ($vatable === 'Yes') ? floatval($_POST['vat'] ?? 0) : 0;
        
        $operational_sql = "INSERT INTO pre_proforma (
                                file_number, all_in, all_in_amount, category, 
                                cost_code, cost_description, charge, vatable, 
                                vat_amount, currency, created_at
                            ) VALUES (?, ?, ?, 'Operational', '1-101', 'Agency Fee', ?, ?, ?, ?, NOW())";
        
        $operational_stmt = $conn->prepare($operational_sql);
        $operational_stmt->bind_param(
            'ssddsss',
            $file_number, $all_in, $all_in_amount, $agency_fees, 
            $vatable, $vat_amount, $currency
        );
        $operational_stmt->execute();
        
        // Insert non-operational costs
        if (isset($_POST['cost_reference']) && is_array($_POST['cost_reference'])) {
            $cost_references = $_POST['cost_reference'];
            $charges = $_POST['charge'];
            
            $non_op_sql = "INSERT INTO pre_proforma (
                                file_number, all_in, all_in_amount, category, 
                                cost_code, cost_description, charge, vatable, 
                                vat_amount, currency, created_at
                            ) VALUES (?, NULL, NULL, 'Non-Operational', ?, ?, ?, 'No', 0, ?, NOW())";
            
            $non_op_stmt = $conn->prepare($non_op_sql);
            
            foreach ($cost_references as $i => $cost_code) {
                if (empty($cost_code) || empty($charges[$i])) continue;
                
                // Get cost description
                $desc_query = "SELECT description FROM cost_reference WHERE code = ? LIMIT 1";
                $desc_stmt = $conn->prepare($desc_query);
                $desc_stmt->bind_param('s', $cost_code);
                $desc_stmt->execute();
                $desc_result = $desc_stmt->get_result();
                $cost_description = ($desc_result->num_rows > 0) 
                    ? $desc_result->fetch_assoc()['description'] 
                    : '';
                
                $charge_amount = floatval($charges[$i]);
                
                $non_op_stmt->bind_param(
                    'sssds',
                    $file_number, $cost_code, $cost_description, 
                    $charge_amount, $currency
                );
                $non_op_stmt->execute();
            }
        }
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Pre-proforma data updated successfully";
        header('Location: view_file.php?id=' . $file_id . '#pre-proforma');
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error updating pre-proforma: " . $e->getMessage();
        header('Location: edit_pre_proforma.php?file_number=' . $file_number);
        exit();
    }
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Pre-Proforma')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css">
    <style>
        .file-details-card {
            margin-bottom: 1.5rem;
        }
        .file-header {
            padding: 1rem;
            border-bottom: 1px solid #e9e9ef;
            background-color: #f8f9fa;
        }
        .file-info-label {
            font-weight: 600;
            color: #495057;
        }
        /* Cost container styles */
        .cost-row {
            position: relative;
            padding: 0.75rem;
            border-radius: 0.25rem;
            transition: background-color 0.2s;
        }
        .cost-row:hover {
            background-color: #f8f9fa;
        }
        .remove-row {
            margin-bottom: 1rem;
        }
        /* Select2 custom styling */
        .select2-container--default .select2-selection--single {
            height: 38px;
            border-color: #ced4da;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
        
        .red-text {
            color: red;
        }
        
        .total-row {
            font-weight: bold;
            background-color: #f2f2f2;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Shipment Management', 'title' => 'Edit Pre-Proforma')); ?>

                    <div class="row">
                        <div class="col-12">
                            <!-- File Info Header -->
                            <div class="card file-details-card">
                                <div class="card-header file-header d-flex align-items-center">
                                    <h4 class="card-title mb-0 flex-grow-1">
                                        Edit Pre-Proforma for <?php echo htmlspecialchars($file_number); ?>
                                    </h4>
                                    <div class="flex-shrink-0">
                                        <a href="view_file.php?id=<?php echo $file_id; ?>#pre-proforma" class="btn btn-sm btn-primary">
                                            <i class="ri-arrow-left-line align-bottom me-1"></i> Back to File
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>File Number:</strong> <?php echo htmlspecialchars($file_number); ?></p>
                                            <p><strong>Customer:</strong> <?php echo htmlspecialchars($file['first_name'] . ' ' . $file['last_name']); ?></p>
                                            <p><strong>Destination:</strong> <?php echo htmlspecialchars($file['destination']); ?></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>Created Date:</strong> <?php echo date('Y-m-d', strtotime($file['created_date'])); ?></p>
                                            <p><strong>Consignee:</strong> <?php echo htmlspecialchars($file['consignee_name']); ?></p>
                                            <p><strong>Currency:</strong> <?php echo htmlspecialchars($file['currency']); ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pre-Proforma Edit Form -->
                    <form method="POST" id="editPreProformaForm">
                        <input type="hidden" name="file_number" value="<?php echo $file_number; ?>">
                        <input type="hidden" name="file_id" value="<?php echo $file_id; ?>">
                        
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5>Operational Costs</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <input type="hidden" name="currency" value="<?php echo $file['currency']; ?>">
                                            <div class="col-sm-4">
                                                <div class="form-group mb-3">
                                                    <label class="form-label">Agency Fees <span class="red-text">*</span></label>
                                                    <input type="text" class="form-control" id="agency-fees" name="agency_fees" 
                                                           value="<?php echo $operational_data ? $operational_data['charge'] : ''; ?>" required>
                                                </div>
                                            </div>
                                            <div class="col-lg-4">
                                                <label class="form-label">Vatable:</label>
                                                <div class="row">
                                                    <div class="col-lg-6">
                                                        <div class="form-check">
                                                            <input type="radio" class="form-check-input" id="customCheck1" name="vatable" value="Yes" 
                                                                   onclick="toggleVat()" <?php echo ($operational_data && $operational_data['vatable'] == 'Yes') ? 'checked' : ''; ?>>
                                                            <label class="form-check-label" for="customCheck1">Yes</label>
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-6">
                                                        <div class="form-check">
                                                            <input type="radio" class="form-check-input" id="customCheck2" name="vatable" value="No" 
                                                                   onclick="toggleVat()" <?php echo (!$operational_data || $operational_data['vatable'] == 'No') ? 'checked' : ''; ?>>
                                                            <label class="form-check-label" for="customCheck2">No</label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-sm-4">
                                                <div class="form-group mb-3">
                                                    <label class="form-label">VAT (18%)</label>
                                                    <input type="text" class="form-control" id="vat" name="vat" 
                                                           value="<?php echo ($operational_data && $operational_data['vatable'] == 'Yes') ? $operational_data['vat_amount'] : ''; ?>" 
                                                           style="<?php echo ($operational_data && $operational_data['vatable'] == 'Yes') ? '' : 'display:none;'; ?>" readonly>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-lg-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5>All In Charges</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-lg-5">
                                                <label class="form-label">Available:</label>
                                                <div class="row">
                                                    <div class="col-lg-6">
                                                        <div class="form-check">
                                                            <input type="radio" class="form-check-input" id="customCheckA" name="allin" value="Yes" 
                                                                   onclick="toggleAllIn()" <?php echo ($all_in_data) ? 'checked' : ''; ?>>
                                                            <label class="form-check-label" for="customCheckA">Yes</label>
                                                        </div>
                                                    </div>
                                                    <div class="col-lg-6">
                                                        <div class="form-check">
                                                            <input type="radio" class="form-check-input" id="customCheckB" name="allin" value="No" 
                                                                   onclick="toggleAllIn()" <?php echo (!$all_in_data) ? 'checked' : ''; ?>>
                                                            <label class="form-check-label" for="customCheckB">No</label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-sm-7">
                                                <div class="form-group mb-3">
                                                    <label class="form-label">All In Amount</label>
                                                    <input type="text" class="form-control" id="all-in" name="all_in_amount" 
                                                           value="<?php echo $all_in_data ? $all_in_data['all_in_amount'] : ''; ?>" 
                                                           style="<?php echo ($all_in_data) ? '' : 'display:none;'; ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">Non-Operational Costs</h5>
                                        <button type="button" class="btn btn-primary btn-sm" id="add-row-btn">
                                            <i class="ri-add-line align-middle"></i> Add Row
                                        </button>
                                    </div>
                                    <div class="card-body">
                                        <div id="cost-container">
                                            <?php if (empty($non_operational_data)): ?>
                                            <!-- Default empty row if no existing data -->
                                            <div class="row mb-3 cost-row">
                                                <div class="col-sm-6">
                                                    <label class="form-label">Select Non-Operational Cost <span class="red-text">*</span></label>
                                                    <select class="form-control cost-reference" name="cost_reference[]" required>
                                                        <?php
                                                        $sql = "SELECT code, description FROM cost_reference WHERE category = 'Non-Operational'";
                                                        $result = $conn->query($sql);

                                                        echo "<option value=''>Please Select Cost</option>";

                                                        if ($result->num_rows > 0) {
                                                            while($row = $result->fetch_assoc()) {
                                                                $option_label = $row['code'] . ' - ' . $row['description'];
                                                                echo "<option value='" . $row['code'] . "'>" . $option_label . "</option>";
                                                            }
                                                        } else {
                                                            echo "<option value=''>No options found</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                                <div class="col-sm-4">
                                                    <div class="form-group">
                                                        <label class="form-label">Enter Charge <span class="red-text">*</span></label>
                                                        <input type="text" class="form-control charge-input" placeholder="Enter value" name="charge[]" required>
                                                    </div>
                                                </div>
                                                <div class="col-sm-2 d-flex align-items-end">
                                                    <button type="button" class="btn btn-danger btn-sm remove-row" style="display: none;">
                                                        <i class="ri-delete-bin-line"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <?php else: ?>
                                            <!-- Existing non-operational cost rows -->
                                            <?php foreach ($non_operational_data as $index => $item): ?>
                                            <div class="row mb-3 cost-row">
                                                <div class="col-sm-6">
                                                    <label class="form-label">Select Non-Operational Cost <span class="red-text">*</span></label>
                                                    <select class="form-control cost-reference" name="cost_reference[]" required>
                                                        <?php
                                                        $sql = "SELECT code, description FROM cost_reference WHERE category = 'Non-Operational'";
                                                        $result = $conn->query($sql);

                                                        echo "<option value=''>Please Select Cost</option>";

                                                        if ($result->num_rows > 0) {
                                                            while($row = $result->fetch_assoc()) {
                                                                $option_label = $row['code'] . ' - ' . $row['description'];
                                                                $selected = ($row['code'] == $item['cost_code']) ? 'selected' : '';
                                                                echo "<option value='" . $row['code'] . "' $selected>" . $option_label . "</option>";
                                                            }
                                                        } else {
                                                            echo "<option value=''>No options found</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                                <div class="col-sm-4">
                                                    <div class="form-group">
                                                        <label class="form-label">Enter Charge <span class="red-text">*</span></label>
                                                        <input type="text" class="form-control charge-input" placeholder="Enter value" 
                                                               name="charge[]" value="<?php echo $item['charge']; ?>" required>
                                                    </div>
                                                </div>
                                                <div class="col-sm-2 d-flex align-items-end">
                                                    <button type="button" class="btn btn-danger btn-sm remove-row" 
                                                            style="<?php echo ($index === 0 && count($non_operational_data) === 1) ? 'display: none;' : ''; ?>">
                                                        <i class="ri-delete-bin-line"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <?php endforeach; ?>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- Totals Row -->
                                        <div class="row mt-4 total-row">
                                            <div class="col-sm-6 text-end">
                                                <strong>Total Non-Operational Costs:</strong>
                                            </div>
                                            <div class="col-sm-4">
                                                <div id="totalNonOpCosts" class="form-control-plaintext">
                                                    <?php echo $file['currency']; ?> 0.00
                                                </div>
                                            </div>
                                            <div class="col-sm-2"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Summary Section -->
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h5>Pre-Proforma Summary</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <tbody>
                                                    <tr>
                                                        <th width="60%">Agency Fees</th>
                                                        <td id="summaryCost1"><?php echo $file['currency']; ?> 0.00</td>
                                                    </tr>
                                                    <tr id="vatRow" style="<?php echo ($operational_data && $operational_data['vatable'] == 'Yes') ? '' : 'display:none;'; ?>">
                                                        <th>VAT Amount (18%)</th>
                                                        <td id="summaryVAT"><?php echo $file['currency']; ?> 0.00</td>
                                                    </tr>
                                                    <tr>
                                                        <th>Non-Operational Costs</th>
                                                        <td id="summaryNonOp"><?php echo $file['currency']; ?> 0.00</td>
                                                    </tr>
                                                    <tr class="table-light">
                                                        <th>Total Amount</th>
                                                        <td id="summaryTotal"><?php echo $file['currency']; ?> 0.00</td>
                                                    </tr>
                                                    <tr id="allInRow" class="table-success" style="<?php echo ($all_in_data) ? '' : 'display:none;'; ?>">
                                                        <th>All-In Amount</th>
                                                        <td id="summaryAllIn"><?php echo $file['currency']; ?> 0.00</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-12 text-end">
                                <a href="view_file.php?id=<?php echo $file_id; ?>#pre-proforma" class="btn btn-outline-secondary me-2">Cancel</a>
                                <button type="submit" class="btn btn-primary">Save Pre-Proforma</button>
                            </div>
                        </div>
                    </form>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
   // Initialize Select2 and setup event listeners
   initializeSelect2Elements();
   setupEventListeners();
   updateSummary();
});

function initializeSelect2Elements() {
   $('.cost-reference').each(function() {
       if (!$(this).hasClass('select2-hidden-accessible')) {
           $(this).select2({
               placeholder: 'Select a cost reference',
               allowClear: true,
               width: '100%'
           });
       }
   });
}

function setupEventListeners() {
   // All In toggle
   const allinRadios = document.querySelectorAll('input[name="allin"]');
   allinRadios.forEach(radio => {
       radio.addEventListener('change', function() {
           toggleAllIn();
           calculateAgencyFees();
           updateSummary();
       });
   });

   // All In amount change
   const allInInput = document.getElementById('all-in');
   if (allInInput) {
       allInInput.addEventListener('input', function() {
           calculateAgencyFees();
           updateSummary();
       });
   }

   // Agency fees input change
   const agencyFeesInput = document.getElementById('agency-fees');
   if (agencyFeesInput) {
       agencyFeesInput.addEventListener('input', function() {
           calculateVAT();
           updateSummary();
       });
   }

   // Add row button
   const addRowBtn = document.getElementById('add-row-btn');
   const container = document.getElementById('cost-container');
   if (addRowBtn && container) {
       addRowBtn.addEventListener('click', function() {
           addNewRow(container);
       });
       
       // Delegate event for removing rows
       container.addEventListener('click', function(e) {
           if (e.target.classList.contains('remove-row') || e.target.closest('.remove-row')) {
               const row = e.target.closest('.cost-row');
               removeRow(row, container);
               calculateAgencyFees();
               updateSummary();
           }
       });
       
       // Delegate for charge input changes
       container.addEventListener('input', function(e) {
           if (e.target.classList.contains('charge-input')) {
               calculateAgencyFees();
               updateSummary();
           }
       });
   }

   // Vatable radios
   const vatableRadios = document.querySelectorAll('input[name="vatable"]');
   vatableRadios.forEach(radio => {
       radio.addEventListener('change', function() {
           toggleVat();
           updateSummary();
       });
   });

   // Initial calculations
   toggleAllIn();
   toggleVat();
   calculateAgencyFees();
}

function toggleAllIn() {
   const allinTextbox = document.getElementById("all-in");
   const allinYes = document.getElementById("customCheckA");
   const allInRow = document.getElementById("allInRow");
   
   if (allinTextbox && allinYes) {
       allinTextbox.style.display = allinYes.checked ? "block" : "none";
       if (allInRow) {
           allInRow.style.display = allinYes.checked ? "" : "none";
       }
   }
}

function toggleVat() {
   const vatTextbox = document.getElementById("vat");
   const vatableYes = document.getElementById("customCheck1");
   const vatRow = document.getElementById("vatRow");
   
   if (vatTextbox && vatableYes) {
       vatTextbox.style.display = vatableYes.checked ? "block" : "none";
       if (vatRow) {
           vatRow.style.display = vatableYes.checked ? "" : "none";
       }
       calculateVAT();
   }
}

function calculateVAT() {
   const agencyFeesInput = document.getElementById('agency-fees');
   const vatInput = document.getElementById('vat');
   const vatableYes = document.getElementById("customCheck1");
   
   if (vatableYes && vatableYes.checked && agencyFeesInput && vatInput && agencyFeesInput.value) {
       const agencyFeesValue = parseFloat(agencyFeesInput.value);
       if (!isNaN(agencyFeesValue)) {
           const vatValue = agencyFeesValue * 0.18;
           vatInput.value = vatValue.toFixed(2);
       }
   } else if (vatInput) {
       vatInput.value = '';
   }
}

function calculateAgencyFees() {
   const allInRadio = document.getElementById('customCheckA');
   const allInInput = document.getElementById('all-in');
   const agencyFeesInput = document.getElementById('agency-fees');
   
   if (!allInRadio || !allInRadio.checked || !allInInput || !agencyFeesInput) {
       return;
   }
   
   const allInValue = parseFloat(allInInput.value);
   if (isNaN(allInValue)) {
       agencyFeesInput.value = '';
       return;
   }
   
   // Calculate sum of non-operational costs
   let nonOpCostsTotal = 0;
   const chargeInputs = document.querySelectorAll('.charge-input');
   chargeInputs.forEach(input => {
       const value = parseFloat(input.value);
       if (!isNaN(value)) {
           nonOpCostsTotal += value;
       }
   });
   
   // Calculate agency fees: All In Amount - (sum of non-operational costs)
   const agencyFees = allInValue - nonOpCostsTotal;
   agencyFeesInput.value = agencyFees.toFixed(2);
   
   // Recalculate VAT if needed
   calculateVAT();
}

function addNewRow(container) {
   const firstRow = container.querySelector('.cost-row');
   if (!firstRow) return;
   
   // Clone the row
   const newRow = firstRow.cloneNode(true);
   
   // Reset values
   const inputs = newRow.querySelectorAll('input');
   inputs.forEach(input => input.value = '');
   
   const select = newRow.querySelector('select.cost-reference');
   if (select) {
       // Reset select
       select.innerHTML = firstRow.querySelector('select.cost-reference').innerHTML;
       select.selectedIndex = 0;
       
       // Clean up any existing Select2
       $(select).removeData();
       $(select).removeClass('select2-hidden-accessible');
       const selectContainer = newRow.querySelector('.select2-container');
       if (selectContainer) {
           selectContainer.parentNode.removeChild(selectContainer);
       }
   }
   
   // Show remove button for all rows
   const removeBtn = newRow.querySelector('.remove-row');
   if (removeBtn) {
       removeBtn.style.display = 'block';
   }
   
   // Show remove button on first row now that we have multiple
   const firstRemoveBtn = firstRow.querySelector('.remove-row');
   if (firstRemoveBtn) {
       firstRemoveBtn.style.display = 'block';
   }
   
   // Add to container
   container.appendChild(newRow);
   
   // Initialize Select2
   const newSelect = newRow.querySelector('select.cost-reference');
   if (newSelect) {
       $(newSelect).select2({
           placeholder: 'Select a cost reference',
           allowClear: true,
           width: '100%'
       });
   }

   // Recalculate after adding row
   calculateAgencyFees();
   updateSummary();
}

function removeRow(row, container) {
   if (container.querySelectorAll('.cost-row').length > 1) {
       // Destroy Select2 if exists
       const select = row.querySelector('select.cost-reference');
       if (select && $(select).hasClass('select2-hidden-accessible')) {
           try {
               $(select).select2('destroy');
           } catch (err) {
               console.log('Error destroying Select2:', err);
               $(select).removeClass('select2-hidden-accessible');
               const selectContainer = row.querySelector('.select2-container');
               if (selectContainer) {
                   selectContainer.parentNode.removeChild(selectContainer);
               }
           }
       }
       row.remove();
       
       // Hide remove button if only one row left
       if (container.querySelectorAll('.cost-row').length === 1) {
           const lastRemoveBtn = container.querySelector('.remove-row');
           if (lastRemoveBtn) {
               lastRemoveBtn.style.display = 'none';
           }
       }
   }
}

function updateSummary() {
   const currency = document.querySelector('input[name="currency"]').value;
   
   // Get agency fees value
   const agencyFeesInput = document.getElementById('agency-fees');
   const agencyFees = parseFloat(agencyFeesInput.value || 0);
   
   // Get VAT value
   const vatInput = document.getElementById('vat');
   const vatableYes = document.getElementById("customCheck1");
   const vatAmount = (vatableYes && vatableYes.checked && vatInput) ? parseFloat(vatInput.value || 0) : 0;
   
   // Calculate sum of non-operational costs
   let nonOpCostsTotal = 0;
   const chargeInputs = document.querySelectorAll('.charge-input');
   chargeInputs.forEach(input => {
       const value = parseFloat(input.value || 0);
       if (!isNaN(value)) {
           nonOpCostsTotal += value;
       }
   });
   
   // Get All-In amount if enabled
   const allInRadio = document.getElementById('customCheckA');
   const allInInput = document.getElementById('all-in');
   const allInAmount = (allInRadio && allInRadio.checked && allInInput) 
       ? parseFloat(allInInput.value || 0) : 0;
   
   // Calculate total
   const totalAmount = agencyFees + vatAmount + nonOpCostsTotal;
   
   // Update summary values
   document.getElementById('summaryCost1').textContent = `${currency} ${agencyFees.toFixed(2)}`;
   document.getElementById('summaryVAT').textContent = `${currency} ${vatAmount.toFixed(2)}`;
   document.getElementById('summaryNonOp').textContent = `${currency} ${nonOpCostsTotal.toFixed(2)}`;
   document.getElementById('summaryTotal').textContent = `${currency} ${totalAmount.toFixed(2)}`;
   document.getElementById('summaryAllIn').textContent = `${currency} ${allInAmount.toFixed(2)}`;
   
   // Update total non-op costs display
   document.getElementById('totalNonOpCosts').textContent = `${currency} ${nonOpCostsTotal.toFixed(2)}`;
}

// Form validation
document.getElementById('editPreProformaForm').addEventListener('submit', function(e) {
   const allInRadio = document.getElementById('customCheckA');
   const allInInput = document.getElementById('all-in');
   const agencyFeesInput = document.getElementById('agency-fees');
   
   // Check if agency fees field is filled
   if (!agencyFeesInput.value) {
       e.preventDefault();
       Swal.fire({
           title: 'Validation Error',
           text: 'Please enter Agency Fees',
           icon: 'error'
       });
       return;
   }
   
   // Validate All-In amount if enabled
   if (allInRadio.checked) {
       if (!allInInput.value) {
           e.preventDefault();
           Swal.fire({
               title: 'Validation Error',
               text: 'Please enter the All-In Amount',
               icon: 'error'
           });
           return;
       }
   }
   
   // Validate non-operational costs
   let hasEmptyNonOp = false;
   const costRows = document.querySelectorAll('.cost-row');
   costRows.forEach(row => {
       const select = row.querySelector('select.cost-reference');
       const charge = row.querySelector('input.charge-input');
       
       if ((select.value && !charge.value) || (!select.value && charge.value)) {
           hasEmptyNonOp = true;
       }
   });
   
   if (hasEmptyNonOp) {
       e.preventDefault();
       Swal.fire({
           title: 'Validation Error',
           text: 'Please complete all non-operational cost rows',
           icon: 'error'
       });
       return;
   }
   
   // Show loading indicator
   Swal.fire({
       title: 'Saving...',
       text: 'Updating pre-proforma data',
       allowOutsideClick: false,
       didOpen: () => {
           Swal.showLoading();
       }
   });
});
    </script>
</body>
</html>