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


if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['branch'])) {
    header('Location: /unauthorized.php');
    exit();
}


$database = new Database();
$conn = $database->getConnection();
$shipment = new Shipment($conn);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);


$filter = isset($_GET['filter']) ? $_GET['filter'] : 'pending';
$validFilters = ['pending', 'approved'];
if (!in_array($filter, $validFilters)) {
    $filter = 'pending';
}


if ($filter === 'approved') {
    $shipments = $shipment->getShipmentsByStatus('shipped');
} else {
    $shipments = $shipment->getShipmentsByStatus('pending');
}

?>

<div class="dashboard-container">
    <div class="main-content">
        <div class="container">
            <h1 class="mb-4">Shipment Approvals Management</h1>
            <a href="/IMS/views/dashboard/branch.php" class="btn btn-sm btn-secondary mb-4">Back to Dashboard</a>

            <?php if (isset($_SESSION['success'])): ?>
                <div class="alert alert-success" role="alert">
                    <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                </div>
            <?php endif; ?>

            <?php if (isset($_SESSION['error'])): ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                </div>
            <?php endif; ?>

            <?php if (isset($_SESSION['debug'])): ?>
                <div class="alert alert-info" role="alert">
                    <strong>Debug:</strong> <?php echo $_SESSION['debug']; unset($_SESSION['debug']); ?>
                </div>
            <?php endif; ?>


            <div class="card mb-4">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" id="shipmentTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <a class="nav-link <?php echo $filter === 'pending' ? 'active' : ''; ?>"
                               href="?filter=pending" role="tab">
                                Pending Approval <span class="badge bg-warning text-dark ms-1"><?php echo $filter === 'pending' ? count($shipments) : 0; ?></span>
                            </a>
                        </li>
                        <li class="nav-item" role="presentation">
                            <a class="nav-link <?php echo $filter === 'approved' ? 'active' : ''; ?>"
                               href="?filter=approved" role="tab">
                                Approved <span class="badge bg-success ms-1"><?php echo $filter === 'approved' ? count($shipments) : 0; ?></span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <?php echo $filter === 'pending' ? 'Shipments Pending Approval' : 'Approved Shipments'; ?>
                        (<?php echo count($shipments); ?>)
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (empty($shipments)): ?>
                        <p class="text-center">
                            <?php echo $filter === 'pending' ? 'No shipments are currently pending for approval.' : 'No approved shipments found.'; ?>
                        </p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Date Created</th>
                                        <th>From Branch</th>
                                        <th>To Branch</th>
                                        <th>Created By</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($shipments as $s): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($s['shipment_date']))); ?></td>
                                            <td><?php echo htmlspecialchars($s['from_branch_name']); ?></td>
                                            <td><?php echo htmlspecialchars($s['to_branch_name']); ?></td>
                                            <td><?php echo htmlspecialchars($s['created_by_name']); ?></td>
                                            <td>
                                                <?php
                                                $statusClass = '';
                                                $statusText = ucfirst($s['status']);
                                                switch($s['status']) {
                                                    case 'pending':
                                                        $statusClass = 'bg-warning text-dark';
                                                        break;
                                                    case 'shipped':
                                                        $statusClass = 'bg-success';
                                                        $statusText = 'Approved';
                                                        break;
                                                    case 'verified':
                                                        $statusClass = 'bg-info';
                                                        break;
                                                    case 'completed':
                                                        $statusClass = 'bg-primary';
                                                        break;
                                                    case 'discrepancy':
                                                        $statusClass = 'bg-danger';
                                                        break;
                                                }
                                                ?>
                                                <span class="badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                                            </td>
                                            <td>
                                                <?php if ($s['status'] === 'pending'): ?>
                                                    <a href="view_for_approval_branch.php?id=<?php echo $s['shipment_id']; ?>" class="btn btn-sm btn-primary">Review & Approve</a>
                                                    <?php if ($userBranchId == $s['from_branch_id']): ?>
                                                        <form action="delete_pending_shipment.php" method="POST" class="d-inline" onsubmit="return confirm('Delete this pending shipment and return its items to the origin branch?');">
                                                            <input type="hidden" name="shipment_id" value="<?php echo (int)$s['shipment_id']; ?>">
                                                            <input type="hidden" name="redirect_to" value="pending_approvals_branch.php">
                                                            <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
                                                        </form>
                                                    <?php endif; ?>
                                                <?php elseif ($s['status'] === 'shipped'): ?>
                                                    <a href="view_for_approval_branch.php?id=<?php echo $s['shipment_id']; ?>" class="btn btn-sm btn-info">View Details</a>
                                                <?php else: ?>
                                                    <a href="view_for_approval_branch.php?id=<?php echo $s['shipment_id']; ?>" class="btn btn-sm btn-secondary">View</a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../../includes/footer.php'; ?>
