<?php
session_start();
include 'layouts/dbconn.php';
require_once 'note-functions.php';

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

// 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'];
}

// Check user 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
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Check if user has permission to view
$can_view = hasPermission($role_id, 'view');
$can_edit = hasPermission($role_id, 'edit');
$can_approve = hasPermission($role_id, 'approve');
$can_delete = hasPermission($role_id, 'delete');

if (!$can_view) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d', strtotime($date));
}

// Handle status change if user has permission
if (isset($_GET['action']) && isset($_GET['id']) && ($can_approve || $can_edit)) {
    $action = $_GET['action'];
    $note_id = intval($_GET['id']);
    $new_status = '';
    
    if ($action === 'approve' && $can_approve) {
        // Process approval
        if (processNoteApproval($conn, $note_id, 'approve', $user_id)) {
            $_SESSION['success_message'] = "Debit note has been approved successfully.";
        } else {
            $_SESSION['error_message'] = "Failed to approve the debit note.";
        }
    } else if ($action === 'deny' && $can_approve) {
        // Process denial
        if (processNoteApproval($conn, $note_id, 'deny', $user_id)) {
            $_SESSION['success_message'] = "Debit note has been denied.";
        } else {
            $_SESSION['error_message'] = "Failed to deny the debit note.";
        }
    } else if ($action === 'cancel' && $can_edit) {
        // Cancel the note
        $sql = "UPDATE notes SET status = 'cancelled' WHERE note_id = ? AND note_type = 'debit'";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $note_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Debit note has been cancelled.";
        } else {
            $_SESSION['error_message'] = "Failed to cancel the debit note.";
        }
    }
    
    // Redirect to avoid resubmission
    header('Location: debit_note_list.php');
    exit();
}

// Handle delete if user has permission
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && $can_delete) {
    $note_id = intval($_GET['id']);
    
    $sql = "DELETE FROM notes WHERE note_id = ? AND note_type = 'debit'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $note_id);
    
    if ($stmt->execute()) {
        $_SESSION['success_message'] = "Debit note has been deleted successfully.";
    } else {
        $_SESSION['error_message'] = "Failed to delete the debit note.";
    }
    
    // Redirect to avoid resubmission
    header('Location: debit_note_list.php');
    exit();
}

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
$offset = ($page - 1) * $limit;

// Search and filtering
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';
$customer_filter = isset($_GET['customer_id']) ? intval($_GET['customer_id']) : 0;
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';

// Build query based on filters
$params = [];
$types = '';

$sql_count = "SELECT COUNT(*) as total FROM notes WHERE note_type = 'debit'";
$sql = "SELECT n.*, c.first_name, c.last_name, u.username as created_by, ua.username as approved_by
        FROM notes n
        LEFT JOIN customers c ON n.customer_id = c.customer_id
        LEFT JOIN users u ON n.user_id = u.user_id
        LEFT JOIN users ua ON n.approved_by = ua.user_id
        WHERE n.note_type = 'debit'";

if (!empty($search)) {
    $search_condition = " AND (n.note_number LIKE ? OR n.file_number LIKE ? OR c.first_name LIKE ? OR c.last_name LIKE ?)";
    $sql_count .= $search_condition;
    $sql .= $search_condition;
    
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

if (!empty($status_filter)) {
    $status_condition = " AND n.status = ?";
    $sql_count .= $status_condition;
    $sql .= $status_condition;
    
    $params[] = $status_filter;
    $types .= 's';
}

if ($customer_filter > 0) {
    $customer_condition = " AND n.customer_id = ?";
    $sql_count .= $customer_condition;
    $sql .= $customer_condition;
    
    $params[] = $customer_filter;
    $types .= 'i';
}

if (!empty($date_from)) {
    $date_from_condition = " AND n.issue_date >= ?";
    $sql_count .= $date_from_condition;
    $sql .= $date_from_condition;
    
    $params[] = $date_from;
    $types .= 's';
}

if (!empty($date_to)) {
    $date_to_condition = " AND n.issue_date <= ?";
    $sql_count .= $date_to_condition;
    $sql .= $date_to_condition;
    
    $params[] = $date_to;
    $types .= 's';
}

// Get total count for pagination
$stmt_count = $conn->prepare($sql_count);
if (!empty($params)) {
    $stmt_count->bind_param($types, ...$params);
}
$stmt_count->execute();
$result_count = $stmt_count->get_result();
$row_count = $result_count->fetch_assoc();
$total_records = $row_count['total'];
$total_pages = ceil($total_records / $limit);

// Add sorting and pagination to the main query
$sql .= " ORDER BY n.issue_date DESC, n.note_id DESC LIMIT $offset, $limit";

// Execute the main query
$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// Get customer list for filter
$sql_customers = "SELECT customer_id, first_name, last_name FROM customers ORDER BY first_name, last_name";
$result_customers = $conn->query($sql_customers);
$customers = [];
if ($result_customers->num_rows > 0) {
    while ($row = $result_customers->fetch_assoc()) {
        $customers[] = $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 = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Debit Notes List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/buttons.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/datatables/responsive.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Daterangepicker css -->
    <link rel="stylesheet" href="assets/libs/flatpickr/flatpickr.min.css">
    
    <style>
        .dataTables_filter {
            margin-bottom: 10px;
        }
        .search-box {
            position: relative;
        }
        .search-box .form-control {
            padding-left: 40px;
        }
        .search-box .search-icon {
            position: absolute;
            left: 13px;
            top: 50%;
            transform: translateY(-50%);
            color: #74788d;
        }
        .action-btn {
            margin-right: 5px;
        }
        .badge-status {
            padding: 5px 8px;
            font-size: 12px;
        }
        .filters-section {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .filters-section .btn-reset {
            height: 38px;
        }
    </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' => 'Finance', 'title' => 'Debit Notes List')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Debit Notes</h5>
                                    <div>
                                        <?php if ($can_edit): ?>
                                        <a href="create_debit_note.php" class="btn btn-primary btn-sm">
                                            <i class="ri-add-line align-bottom"></i> Create Debit Note
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <!-- Filters Section -->
                                    <div class="filters-section">
                                        <form action="" method="GET" class="row g-3">
                                            <div class="col-md-4 col-sm-12">
                                                <div class="search-box">
                                                    <input type="text" name="search" class="form-control" placeholder="Search for note #, file #, customer..." value="<?php echo htmlspecialchars($search); ?>">
                                                    <i class="ri-search-line search-icon"></i>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-2 col-sm-6">
                                                <select name="status" class="form-select">
                                                    <option value="">All Statuses</option>
                                                    <option value="draft" <?php echo $status_filter === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                                    <option value="issued" <?php echo $status_filter === 'issued' ? 'selected' : ''; ?>>Issued</option>
                                                    <option value="approved" <?php echo $status_filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                    <option value="denied" <?php echo $status_filter === 'denied' ? 'selected' : ''; ?>>Denied</option>
                                                    <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-2 col-sm-6">
                                                <select name="customer_id" class="form-select">
                                                    <option value="">All Customers</option>
                                                    <?php foreach ($customers as $customer): ?>
                                                    <option value="<?php echo $customer['customer_id']; ?>" <?php echo $customer_filter === $customer['customer_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-1 col-sm-6">
                                                <input type="text" name="date_from" class="form-control flatpickr-input" placeholder="From Date" value="<?php echo $date_from; ?>">
                                            </div>
                                            
                                            <div class="col-md-1 col-sm-6">
                                                <input type="text" name="date_to" class="form-control flatpickr-input" placeholder="To Date" value="<?php echo $date_to; ?>">
                                            </div>
                                            
                                            <div class="col-md-2 col-sm-12 d-flex gap-2">
                                                <button type="submit" class="btn btn-primary w-100">Filter</button>
                                                <a href="debit_note_list.php" class="btn btn-light btn-reset">Reset</a>
                                            </div>
                                        </form>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table id="debit-notes-table" class="table table-bordered dt-responsive nowrap table-striped align-middle">
                                            <thead>
                                                <tr>
                                                    <th>Note Number</th>
                                                    <th>Customer</th>
                                                    <th>Issue Date</th>
                                                    <th>Amount</th>
                                                    <th>File Number</th>
                                                    <th>Status</th>
                                                    <th>Created By</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                if ($result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $note_id = $row['note_id'];
                                                        $note_number = $row['note_number'];
                                                        $customer_name = $row['first_name'] . ' ' . $row['last_name'];
                                                        $issue_date = formatDate($row['issue_date']);
                                                        $amount = $row['currency'] . ' ' . number_format($row['total_amount'], 2);
                                                        $file_number = $row['file_number'] ?: 'N/A';
                                                        $status = $row['status'];
                                                        $created_by = $row['created_by'];
                                                        
                                                        // Determine status badge class
                                                        $status_badge_class = 'bg-secondary';
                                                        switch ($status) {
                                                            case 'draft':
                                                                $status_badge_class = 'bg-secondary';
                                                                break;
                                                            case 'issued':
                                                                $status_badge_class = 'bg-primary';
                                                                break;
                                                            case 'approved':
                                                                $status_badge_class = 'bg-success';
                                                                break;
                                                            case 'denied':
                                                                $status_badge_class = 'bg-danger';
                                                                break;
                                                            case 'cancelled':
                                                                $status_badge_class = 'bg-dark';
                                                                break;
                                                        }
                                                        
                                                        echo "<tr>";
                                                        echo "<td><a href='view_debit_note.php?id=$note_id' class='text-primary fw-medium'>$note_number</a></td>";
                                                        echo "<td>$customer_name</td>";
                                                        echo "<td>$issue_date</td>";
                                                        echo "<td>$amount</td>";
                                                        echo "<td>" . ($row['file_number'] ? "<a href='view_file.php?file_number=$file_number' class='text-info'>$file_number</a>" : "N/A") . "</td>";
                                                        echo "<td><span class='badge $status_badge_class badge-status'>" . ucfirst($status) . "</span></td>";
                                                        echo "<td>$created_by</td>";
                                                        echo "<td>";
                                                        
                                                        // View button
                                                        echo "<a href='view_debit_note.php?id=$note_id' class='btn btn-sm btn-info action-btn' title='View'>";
                                                        echo "<i class='ri-eye-line'></i>";
                                                        echo "</a>";
                                                        
                                                        // Edit button - only for draft status and if user has edit permission
                                                        if ($can_edit && ($status == 'draft' || $status == 'issued')) {
                                                            echo "<a href='edit_debit_note.php?id=$note_id' class='btn btn-sm btn-primary action-btn' title='Edit'>";
                                                            echo "<i class='ri-edit-2-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Cancel button - only for issued notes
                                                        if ($can_edit && $status == 'issued') {
                                                            echo "<a href='javascript:void(0);' class='btn btn-sm btn-warning action-btn cancel-note' data-id='$note_id' title='Cancel'>";
                                                            echo "<i class='ri-close-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Approve/Deny buttons - only for issued notes and if user has approve permission
                                                        if ($can_approve && $status == 'issued') {
                                                            echo "<a href='javascript:void(0);' class='btn btn-sm btn-success action-btn approve-note' data-id='$note_id' title='Approve'>";
                                                            echo "<i class='ri-check-line'></i>";
                                                            echo "</a>";
                                                            
                                                            echo "<a href='javascript:void(0);' class='btn btn-sm btn-danger action-btn deny-note' data-id='$note_id' title='Deny'>";
                                                            echo "<i class='ri-close-circle-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Delete button - only for draft status and if user has delete permission
                                                        if ($can_delete && $status == 'draft') {
                                                            echo "<a href='javascript:void(0);' class='btn btn-sm btn-danger action-btn delete-note' data-id='$note_id' title='Delete'>";
                                                            echo "<i class='ri-delete-bin-line'></i>";
                                                            echo "</a>";
                                                        }
                                                        
                                                        // Print button for all notes
                                                        echo "<a href='print_debit_note.php?id=$note_id' class='btn btn-sm btn-secondary action-btn' title='Print' target='_blank'>";
                                                        echo "<i class='ri-printer-line'></i>";
                                                        echo "</a>";
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='8' class='text-center'>No debit notes found</td></tr>";
                                                }
                                                
                                                $conn->close();
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                    <div class="d-flex justify-content-end mt-3">
                                        <nav aria-label="Page navigation">
                                            <ul class="pagination">
                                                <?php if ($page > 1): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=1<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($status_filter) ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $customer_filter > 0 ? '&customer_id=' . $customer_filter : ''; ?><?php echo !empty($date_from) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo !empty($date_to) ? '&date_to=' . urlencode($date_to) : ''; ?>" aria-label="First">
                                                        <span aria-hidden="true">&laquo;&laquo;</span>
                                                    </a>
                                                </li>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($status_filter) ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $customer_filter > 0 ? '&customer_id=' . $customer_filter : ''; ?><?php echo !empty($date_from) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo !empty($date_to) ? '&date_to=' . urlencode($date_to) : ''; ?>" aria-label="Previous">
                                                        <span aria-hidden="true">&laquo;</span>
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                                
                                                <?php
                                                $start_page = max(1, $page - 2);
                                                $end_page = min($total_pages, $page + 2);
                                                
                                                for ($i = $start_page; $i <= $end_page; $i++):
                                                ?>
                                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($status_filter) ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $customer_filter > 0 ? '&customer_id=' . $customer_filter : ''; ?><?php echo !empty($date_from) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo !empty($date_to) ? '&date_to=' . urlencode($date_to) : ''; ?>">
                                                        <?php echo $i; ?>
                                                    </a>
                                                </li>
                                                <?php endfor; ?>
                                                
                                                <?php if ($page < $total_pages): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($status_filter) ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $customer_filter > 0 ? '&customer_id=' . $customer_filter : ''; ?><?php echo !empty($date_from) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo !empty($date_to) ? '&date_to=' . urlencode($date_to) : ''; ?>" aria-label="Next">
                                                        <span aria-hidden="true">&raquo;</span>
                                                    </a>
                                                </li>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $total_pages; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($status_filter) ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $customer_filter > 0 ? '&customer_id=' . $customer_filter : ''; ?><?php echo !empty($date_from) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo !empty($date_to) ? '&date_to=' . urlencode($date_to) : ''; ?>" aria-label="Last">
                                                        <span aria-hidden="true">&raquo;&raquo;</span>
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </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'; ?>
    
    <!-- Flatpickr js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize flatpickr date pickers
            $(".flatpickr-input").flatpickr({
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Handle approve note
            $('.approve-note').on('click', function() {
                const noteId = $(this).data('id');
                
                Swal.fire({
                    title: 'Approve Debit Note',
                    text: "Are you sure you want to approve this debit note?",
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, approve it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'debit_note_list.php?action=approve&id=' + noteId;
                    }
                });
            });
            
            // Handle deny note
            $('.deny-note').on('click', function() {
                const noteId = $(this).data('id');
                
                Swal.fire({
                    title: 'Deny Debit Note',
                    text: "Are you sure you want to deny this debit note?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, deny it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'debit_note_list.php?action=deny&id=' + noteId;
                    }
                });
            });
            
            // Handle cancel note
            $('.cancel-note').on('click', function() {
                const noteId = $(this).data('id');
                
                Swal.fire({
                    title: 'Cancel Debit Note',
                    text: "Are you sure you want to cancel this debit note?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, cancel it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'debit_note_list.php?action=cancel&id=' + noteId;
                    }
                });
            });
            
            // Handle delete note
            $('.delete-note').on('click', function() {
                const noteId = $(this).data('id');
                
                Swal.fire({
                    title: 'Delete Debit Note',
                    text: "Are you sure you want to delete this debit note? This action cannot be undone!",
                    icon: 'error',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'debit_note_list.php?action=delete&id=' + noteId;
                    }
                });
            });
            
            // Show success message with SweetAlert if present
            <?php if (isset($_SESSION['swal_success'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo $_SESSION['swal_success']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_success']); endif; ?>
            
            // Show error message with SweetAlert if present
            <?php if (isset($_SESSION['swal_error'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '<?php echo $_SESSION['swal_error']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_error']); endif; ?>
        });
    </script>

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