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

// Check if user is logged in and has admin role
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email 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'];
}

// Handle search parameters
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

// 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";
}

// Function to format date
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));
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Delete Records')); ?>
    <?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 Alerts CSS -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</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' => 'Administration', 'title' => 'Delete Records')); ?>

                    <?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">Files Available for Deletion</h5>
                                    <div>
                                        <a href="index.php" class="btn btn-primary btn-sm">
                                            <i class="ri-dashboard-line align-bottom"></i> Back to Dashboard
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6 col-sm-12 mb-2 mb-md-0">
                                            <form action="" method="GET" class="d-flex">
                                                <div class="input-group">
                                                    <input type="text" name="search" class="form-control" placeholder="Search file number, customer, destination..." value="<?php echo htmlspecialchars($search); ?>">
                                                    <button type="submit" class="btn btn-primary">Search</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>

                                    <div class="alert alert-warning">
                                        <i class="ri-alert-line me-2"></i>
                                        <strong>Warning:</strong> Deleting files will permanently remove them from the system. Only files without proforma, pre-proforma, or invoice records can be deleted.
                                    </div>

                                    <div class="table-responsive">
                                        <table id="files-table" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>File Number</th>
                                                    <th>Customer</th>
                                                    <th>Consignee</th>
                                                    <th>Destination</th>
                                                    <th>Created Date</th>
                                                    <th>Type</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Query to get files eligible for deletion
                                                $sql = "
                                                    SELECT 
                                                        f.id, 
                                                        f.file_number, 
                                                        c.first_name AS customer_name,
                                                        f.consignee_name,
                                                        f.destination, 
                                                        f.created_date,
                                                        f.`local/transit` AS file_type
                                                    FROM 
                                                        files f
                                                    LEFT JOIN 
                                                        customers c ON f.customer = c.customer_id
                                                    WHERE 
                                                        NOT EXISTS (
                                                            SELECT 1 FROM pre_proforma pp WHERE pp.file_number = f.file_number
                                                        )
                                                        AND NOT EXISTS (
                                                            SELECT 1 FROM proforma pr WHERE pr.file_number = f.file_number
                                                        )
                                                        AND NOT EXISTS (
                                                            SELECT 1 FROM invoices i WHERE i.file_number = f.file_number
                                                        )
                                                ";
                                                
                                                // Add search condition if search parameter exists
                                                if (!empty($search)) {
                                                    $sql .= " AND (
                                                        f.file_number LIKE '%$search%' OR 
                                                        c.first_name LIKE '%$search%' OR 
                                                        f.consignee_name LIKE '%$search%' OR
                                                        f.destination LIKE '%$search%'
                                                    )";
                                                }
                                                
                                                $sql .= " ORDER BY f.created_date DESC";
                                                
                                                $result = $conn->query($sql);
                                                
                                                if ($result && $result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $file_id = $row['id'];
                                                        $file_number = $row['file_number'];
                                                        $customer_name = $row['customer_name'] ?: 'N/A';
                                                        $consignee_name = $row['consignee_name'];
                                                        $destination = $row['destination'];
                                                        $created_date = formatDate($row['created_date']);
                                                        $file_type = $row['file_type'] == 1 ? 'Local' : 'Transit';
                                                        
                                                        echo "<tr>";
                                                        echo "<td><a href='view_file.php?id=$file_id' class='text-primary'>$file_number</a></td>";
                                                        echo "<td>$customer_name</td>";
                                                        echo "<td>$consignee_name</td>";
                                                        echo "<td>$destination</td>";
                                                        echo "<td>$created_date</td>";
                                                        echo "<td>$file_type</td>";
                                                        echo "<td class='text-center'>";
                                                        
                                                        // View button
                                                        echo "<a href='view_file.php?id=$file_id' class='btn btn-sm btn-info me-2' title='View File'>";
                                                        echo "<i class='ri-eye-line'></i>";
                                                        echo "</a>";
                                                        
                                                        // Delete button
                                                        echo "<button type='button' class='btn btn-sm btn-danger delete-btn' data-id='$file_id' data-number='$file_number' title='Delete File'>";
                                                        echo "<i class='ri-delete-bin-line'></i>";
                                                        echo "</button>";
                                                        
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='7' class='text-center'>No files available for deletion</td></tr>";
                                                }
                                                
                                                $conn->close();
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </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'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#files-table').DataTable({
                responsive: true,
                lengthChange: true,
                pageLength: 10,
                lengthMenu: [10, 25, 50, 100],
                language: {
                    emptyTable: "No files available for deletion",
                    zeroRecords: "No matching files found"
                }
            });
            
            // Delete button click handler
            $(document).on('click', '.delete-btn', function() {
                var fileId = $(this).data('id');
                var fileNumber = $(this).data('number');
                
                Swal.fire({
                    title: 'Are you sure?',
                    text: "You are about to delete file " + fileNumber + ". This action cannot be undone!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'No, cancel!',
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    reverseButtons: true
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'process_delete.php?file_id=' + fileId;
                    }
                });
            });
        });
    </script>
</body>
</html>