<?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';
require_once __DIR__ . '/../../includes/dashboard_helper.php';


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


$auth = new Auth($conn);


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


if (!isset($_GET['branch_id']) || $_GET['branch_id'] === '') {
    die("No branch selected.");
}
$branch_id = $_GET['branch_id'] === 'all' ? 'all' : (int)$_GET['branch_id'];


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


$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$isWarehouse = ($_SESSION['role'] == 'warehouse');
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);
$isAllBranches = $branch_id === 'all';

if ($isAllBranches && !$isSuperAdmin && !$isWarehouse) {
    die("You don't have permission to view all branch shipments.");
}

$branchDetails = $isAllBranches ? ['branch_name' => 'All Branches'] : $branch->getBranchById($branch_id);
if (!$branchDetails) {
    die("Branch not found.");
}

if (!$isAllBranches && !$isSuperAdmin && !$isWarehouse && $userBranchId != $branch_id) {
    die("You don't have permission to view this branch's shipments.");
}


$type = isset($_GET['type']) ? $_GET['type'] : 'all';
$status = isset($_GET['status']) ? strtolower(trim($_GET['status'])) : 'all';
$validStatuses = ['all', 'pending', 'shipped', 'verified', 'completed', 'delivered', 'discrepancy', 'pending_approval', 'rejected'];
if (!in_array($status, $validStatuses, true)) {
    $status = 'all';
}


$start_date = null;
$end_date = null;
$display_start_date = '';
$display_end_date = '';

if (isset($_GET['start_date']) && !empty($_GET['start_date'])) {
    $display_start_date = $_GET['start_date'];
    $start_date = date('Y-m-d 00:00:00', strtotime($_GET['start_date']));
}

if (isset($_GET['end_date']) && !empty($_GET['end_date'])) {
    $display_end_date = $_GET['end_date'];
    $end_date = date('Y-m-d 23:59:59', strtotime($_GET['end_date']));
}


if ($isAllBranches) {
    $shipmentsQuery = "SELECT s.*,
                              b_from.branch_name AS from_branch_name,
                              b_to.branch_name AS to_branch_name,
                              u.username AS created_by_name
                       FROM shipments s
                       LEFT JOIN branches b_from ON s.from_branch_id = b_from.branch_id
                       LEFT JOIN branches b_to ON s.to_branch_id = b_to.branch_id
                       LEFT JOIN users u ON s.created_by = u.user_id
                       WHERE 1 = 1";

    if ($status !== 'all') {
        $shipmentsQuery .= " AND s.status = :status";
    }
    if (!empty($start_date)) {
        $shipmentsQuery .= " AND DATE(s.shipment_date) >= :start_date";
    }
    if (!empty($end_date)) {
        $shipmentsQuery .= " AND DATE(s.shipment_date) <= :end_date";
    }

    $shipmentsQuery .= " ORDER BY s.shipment_date DESC";
    $shipmentsStmt = $conn->prepare($shipmentsQuery);

    if ($status !== 'all') {
        $shipmentsStmt->bindValue(':status', $status, PDO::PARAM_STR);
    }
    if (!empty($start_date)) {
        $shipmentsStmt->bindValue(':start_date', $start_date);
    }
    if (!empty($end_date)) {
        $shipmentsStmt->bindValue(':end_date', $end_date);
    }

    $shipmentsStmt->execute();
    $shipments = $shipmentsStmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $shipments = $shipment->getBranchShipments($branch_id, $type, $start_date, $end_date);
    if ($status !== 'all') {
        $shipments = array_values(array_filter($shipments, function ($shipmentRow) use ($status) {
            return strtolower($shipmentRow['status'] ?? '') === $status;
        }));
    }
}


$dashboardLink = getDashboardLink('views/shipments/view_shipments.php');
if ($isSuperAdmin) {
    $dashboardLink = 'shipment_dashboard.php';
} elseif ($isWarehouse) {
    $dashboardLink = 'shipment_dashboard.php';
} elseif ($_SESSION['role'] == 'branch_manager') {
    $dashboardLink = '../../dashboard.php';
} else {
    $dashboardLink = '../../dashboard.php';
}
?>

<?php include __DIR__ . '/../../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-delivered {
            background-color: #d4edda;
            color: #155724;
        }
        .status-discrepancy {
            background-color: #f8d7da;
            color: #721c24;
        }
        .no-shipments {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
        .filter-buttons {
            margin-top: 15px;
        }
        .filter-row {
            align-items: end;
        }


        .status-pending_approval {
            background-color: #f0ad4e;
            color: #fff;
        }
        .status-rejected {
            background-color: #d9534f;
            color: #fff;
        }

    </style>
    <a href="<?php echo $dashboardLink; ?>" class="dashboard-return-link">
        <i class="fas fa-arrow-left"></i> Back to Dashboard
    </a>

    <div class="container mt-4">
        <h2 class="text-center mb-4">Shipments for <?php echo htmlspecialchars($branchDetails['branch_name']); ?></h2>

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

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

        <div class="row mb-3">
            <div class="col-md-6">

            </div>
            <div class="col-md-6 text-end">
                <?php if ($isSuperAdmin): ?>

                <?php endif; ?>
            </div>
        </div>


        <div class="row mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title mb-3">Filter Shipments</h5>
                        <form method="GET">
                            <input type="hidden" name="branch_id" value="<?php echo $branch_id; ?>">
                            <input type="hidden" name="type" value="<?php echo $type; ?>">
                            <div class="row filter-row g-3">
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <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 $display_start_date; ?>">
                                </div>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <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 $display_end_date; ?>">
                                </div>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-control" id="status" name="status">
                                        <?php foreach ($validStatuses as $statusOption): ?>
                                            <option value="<?php echo htmlspecialchars($statusOption); ?>" <?php echo $status === $statusOption ? 'selected' : ''; ?>>
                                                <?php echo $statusOption === 'all' ? 'All statuses' : ucfirst(str_replace('_', ' ', $statusOption)); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-lg-3 col-md-12 col-12">
                                    <div class="filter-buttons d-flex gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-filter"></i> Apply Filter
                                        </button>
                                        <a href="?branch_id=<?php echo $branch_id; ?>&type=<?php echo $type; ?>" class="btn btn-outline-secondary">
                                            <i class="fas fa-times"></i> Clear
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <?php if (empty($shipments)): ?>
        <div class="no-shipments">
            <i class="fas fa-box-open fa-3x 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>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>

                <?php foreach ($shipments as $shipment): ?>
                    <?php

                    $link = 'view_shipment.php?id=' . $shipment['shipment_id'];
                    $isApprover = ($_SESSION['role'] == 'admin' || $_SESSION['role'] == 'super_admin');
                    if ($shipment['status'] === 'pending_approval' && $isApprover) {
                        $link = 'approve_shipment.php?id=' . $shipment['shipment_id'];
                    }
                    ?>
                    <tr class="shipment-row" onclick="window.location='<?php echo $link; ?>'">
                        <td><?php echo $shipment['shipment_id']; ?></td>
                        <td><?php echo (new DateTime($shipment['shipment_date']))->format('M d, 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_approval':
                                    $statusClass = 'status-pending_approval';
                                    break;
                                case 'rejected':
                                    $statusClass = 'status-rejected';
                                    break;
                                default:
                                    $statusClass = 'status-' . htmlspecialchars($shipment['status']);
                                    break;
                            }
                            ?>
                            <span class="status-badge <?php echo $statusClass; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $shipment['status'])); ?>
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($shipment['created_by_name']); ?></td>
                        <td onclick="event.stopPropagation();">
                            <?php
                            $canDeletePending = $shipment['status'] === 'pending'
                                && ($isSuperAdmin || $isWarehouse || ($_SESSION['role'] === 'branch' && $userBranchId == $shipment['from_branch_id']));
                            ?>
                            <?php if ($canDeletePending): ?>
                                <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)$shipment['shipment_id']; ?>">
                                    <input type="hidden" name="redirect_to" value="<?php echo htmlspecialchars('view_shipments.php?' . http_build_query($_GET)); ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </form>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

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