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

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

// Check if we have import data
if (!isset($_SESSION['import_data'])) {
    header('Location: import_shipments.php');
    exit();
}

$importData = $_SESSION['import_data'];
$importErrors = $_SESSION['import_errors'] ?? [];

// Handle import submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['approved_rows']) && !empty($_POST['approved_rows'])) {
        try {
            $approvedRows = $_POST['approved_rows'];
            $approvedData = array_intersect_key($importData, array_flip($approvedRows));
            
            $importer = new ShipmentImporter($conn);
            $importer->saveImportedData($approvedData);
            
            // Clear import session data
            unset($_SESSION['import_data']);
            unset($_SESSION['import_errors']);
            
            $_SESSION['success_message'] = "Successfully imported " . count($approvedData) . " shipments.";
            header('Location: file_list.php');
            exit();
        } catch (Exception $e) {
            $_SESSION['error_message'] = "Import failed: " . $e->getMessage();
        }
    } else {
        $_SESSION['error_message'] = "Please select at least one row to import.";
    }
}

include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Verify Import Data')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .table-responsive {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .error-row {
            background-color: #fff3f3;
        }
        .select-all-container {
            margin: 10px 0;
        }
        .row-checkbox {
            width: 18px;
            height: 18px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Shipments', 'title' => 'Verify Import Data')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Verify Import Data</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($_SESSION['error_message'])): ?>
                                        <div class="alert alert-danger">
                                            <?php 
                                            echo $_SESSION['error_message'];
                                            unset($_SESSION['error_message']);
                                            ?>
                                        </div>
                                    <?php endif; ?>

                                    <form action="" method="post" id="importForm">
                                        <div class="select-all-container">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="selectAll">
                                                <label class="form-check-label" for="selectAll">
                                                    Select/Deselect All Valid Rows
                                                </label>
                                            </div>
                                        </div>

                                        <div class="table-responsive">
                                            <table class="table table-bordered table-striped">
                                                <thead>
                                                    <tr>
                                                        <th style="width: 50px;">
                                                            Select
                                                        </th>
                                                        <th>Generated File Number</th>
                                                        <th>Customer ID</th>
                                                        <th>Consignee Name</th>
                                                        <th>Destination</th>
                                                        <th>Container Details</th>
                                                        <th>Status</th>
                                                        <th>Errors/Warnings</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($importData as $index => $row): ?>
                                                        <?php 
                                                        $hasErrors = isset($importErrors[$index]);
                                                        $rowClass = $hasErrors ? 'error-row' : '';
                                                        ?>
                                                        <tr class="<?php echo $rowClass; ?>">
                                                            <td class="text-center">
                                                                <div class="form-check">
                                                                    <input class="form-check-input row-checkbox" type="checkbox" 
                                                                           name="approved_rows[]" value="<?php echo $index; ?>"
                                                                           <?php echo $hasErrors ? 'disabled' : ''; ?>>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php if (isset($row['file_number'])): ?>
                                                                    <strong><?php echo htmlspecialchars($row['file_number']); ?></strong>
                                                                <?php else: ?>
                                                                    <span class="text-danger">Not Generated</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($row['customer']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['consignee_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['destination']); ?></td>
                                                            <td>
                                                                <?php if (!empty($row['container_code'])): ?>
                                                                    <strong>Code:</strong> <?php echo htmlspecialchars($row['container_code']); ?><br>
                                                                    <strong>Size:</strong> <?php echo htmlspecialchars($row['container_size']); ?><br>
                                                                    <strong>Transporter:</strong> <?php echo htmlspecialchars($row['transporter_name']); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">No container details</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($hasErrors): ?>
                                                                    <span class="badge bg-danger">Invalid</span>
                                                                <?php else: ?>
                                                                    <span class="badge bg-success">Valid</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($hasErrors): ?>
                                                                    <ul class="list-unstyled mb-0">
                                                                        <?php foreach ($importErrors[$index] as $error): ?>
                                                                            <li class="text-danger">
                                                                                <i class="ri-error-warning-line align-middle me-1"></i>
                                                                                <?php echo htmlspecialchars($error); ?>
                                                                            </li>
                                                                        <?php endforeach; ?>
                                                                    </ul>
                                                                <?php else: ?>
                                                                    <span class="text-success">
                                                                        <i class="ri-checkbox-circle-line align-middle me-1"></i>
                                                                        Ready to import
                                                                    </span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>

                                        <div class="row mt-3">
                                            <div class="col-12">
                                                <a href="import_shipments.php" class="btn btn-danger me-2">
                                                    <i class="ri-close-line align-bottom me-1"></i> Cancel Import
                                                </a>
                                                <button type="submit" class="btn btn-success" id="importButton">
                                                    <i class="ri-check-double-line align-bottom me-1"></i> Import Selected
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Handle select all checkbox
            const selectAllCheckbox = document.getElementById('selectAll');
            const rowCheckboxes = document.querySelectorAll('.row-checkbox:not([disabled])');

            selectAllCheckbox.addEventListener('change', function() {
                rowCheckboxes.forEach(checkbox => {
                    checkbox.checked = selectAllCheckbox.checked;
                });
            });

            // Update select all state when individual checkboxes change
            rowCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const allChecked = Array.from(rowCheckboxes).every(cb => cb.checked);
                    const noneChecked = Array.from(rowCheckboxes).every(cb => !cb.checked);
                    selectAllCheckbox.checked = allChecked;
                    selectAllCheckbox.indeterminate = !allChecked && !noneChecked;
                });
            });

            // Form submission validation
            document.getElementById('importForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const checkedBoxes = document.querySelectorAll('.row-checkbox:checked');
                if (checkedBoxes.length === 0) {
                    Swal.fire({
                        title: 'No Rows Selected',
                        text: 'Please select at least one valid row to import.',
                        icon: 'warning',
                        confirmButtonText: 'OK'
                    });
                    return;
                }

                Swal.fire({
                    title: 'Confirm Import',
                    text: `Are you sure you want to import ${checkedBoxes.length} selected rows?`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Import',
                    cancelButtonText: 'No, Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        this.submit();
                    }
                });
            });
        });
    </script>
</body>
</html>