<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Shipment.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


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


$userBranchId = $auth->getUserBranch($_SESSION['user_id']);


$branch = new Branch($conn);
$shipment = new Shipment($conn);


$branchDetails = $branch->getBranchById($userBranchId);
if (!$branchDetails) {
    die("Branch not found.");
}


$start_date = isset($_GET['start_date']) && !empty($_GET['start_date']) ? $_GET['start_date'] : null;
$end_date = isset($_GET['end_date']) && !empty($_GET['end_date']) ? $_GET['end_date'] : null;


if ($start_date && strpos($start_date, '/') !== false) {
    $date_parts = explode('/', $start_date);
    if (count($date_parts) === 3) {
        $start_date = sprintf('%04d-%02d-%02d', $date_parts[2], $date_parts[1], $date_parts[0]);
    }
}
if ($end_date && strpos($end_date, '/') !== false) {
    $date_parts = explode('/', $end_date);
    if (count($date_parts) === 3) {
        $end_date = sprintf('%04d-%02d-%02d', $date_parts[2], $date_parts[1], $date_parts[0]);
    }
}


$shipments = $shipment->getBranchShipments($userBranchId, 'all', $start_date, $end_date);
?>

<?php include '../../includes/header.php'; ?>
    <style>
        .shipment-table {
            margin-top: 20px;
        }
        .shipment-row {
            cursor: pointer;
        }
        .shipment-row:hover {
            background-color: #f5f5f5;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: bold;
        }
        .status-pending {
            background-color: #ffeeba;
            color: #856404;
        }
        .status-shipped {
            background-color: #b8daff;
            color: #004085;
        }
        .status-verified {
            background-color: #c3e6cb;
            color: #155724;
        }
        .status-completed {
            background-color: #d4edda;
            color: #155724;
        }
        .status-discrepancy {
            background-color: #f8d7da;
            color: #721c24;
        }
        .no-shipments {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
    </style>

    <div class="container mt-4">
        <div class="row mb-4">
            <div class="col-12">
                <h2>Shipment Records for <?php echo htmlspecialchars($branchDetails['branch_name']); ?></h2>
                <p class="text-muted">View and track all shipments for your branch</p>
            </div>
        </div>


        <div class="row mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Filter Shipments by Date</h5>
                        <form method="GET" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="row g-3" id="filterForm">
                            <div class="col-md-4">
                                <label for="start_date" class="form-label">From Date</label>
                                <input type="date" class="form-control" id="start_date" name="start_date"
                                       value="<?php echo $start_date ? date('Y-m-d', strtotime($start_date)) : ''; ?>"
                                       max="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="end_date" class="form-label">To Date</label>
                                <input type="date" class="form-control" id="end_date" name="end_date"
                                       value="<?php echo $end_date ? date('Y-m-d', strtotime($end_date)) : ''; ?>"
                                       max="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="fas fa-search"></i> Apply Filter
                                </button>
                                <a href="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Clear Filters
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <?php if (empty($shipments)): ?>
            <div class="no-shipments">
                <i class="fas fa-box-open fa-4x mb-3"></i>
                <h4>No shipments found</h4>
                <p>There are no shipments for this branch yet.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive shipment-table">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Shipment #</th>
                            <th>Date</th>
                            <th>From</th>
                            <th>To</th>
                            <th>Status</th>
                            <th>Created By</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($shipments as $shipment): ?>
                            <tr class="shipment-row" onclick="window.location='../shipments/view_shipment.php?id=<?php echo $shipment['shipment_id']; ?>'">
                                <td><?php echo $shipment['shipment_id']; ?></td>
                                <td>
                                    <?php
                                    $date = new DateTime($shipment['shipment_date']);
                                    echo $date->format('M j, Y, g:i a');
                                    ?>
                                </td>
                                <td><?php echo htmlspecialchars($shipment['from_branch_name'] ?? 'Headquarters'); ?></td>
                                <td><?php echo htmlspecialchars($shipment['to_branch_name']); ?></td>
                                <td>
                                    <?php
                                    $statusClass = '';
                                    switch ($shipment['status']) {
                                        case 'pending':
                                            $statusClass = 'status-pending';
                                            break;
                                        case 'shipped':
                                            $statusClass = 'status-shipped';
                                            break;
                                        case 'verified':
                                            $statusClass = 'status-verified';
                                            break;
                                        case 'completed':
                                            $statusClass = 'status-completed';
                                            break;
                                        case 'discrepancy':
                                            $statusClass = 'status-discrepancy';
                                            break;
                                    }
                                    ?>
                                    <span class="status-badge <?php echo $statusClass; ?>">
                                        <?php echo ucfirst($shipment['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($shipment['created_by_name']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const startDateInput = document.getElementById('start_date');
            const endDateInput = document.getElementById('end_date');


            startDateInput.addEventListener('change', function() {
                if (this.value) {
                    endDateInput.min = this.value;

                    if (endDateInput.value && endDateInput.value < this.value) {
                        endDateInput.value = '';
                    }
                } else {
                    endDateInput.min = '';
                }
            });


            document.getElementById('filterForm').addEventListener('submit', function(e) {
                const startDate = startDateInput.value;
                const endDate = endDateInput.value;

                if (startDate && endDate && endDate < startDate) {
                    e.preventDefault();
                    alert('End date cannot be before start date.');
                    endDateInput.focus();
                    return false;
                }
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>