<?php
include '../../includes/header.php';

require_once __DIR__ . '/../../classes/Branch.php';


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


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


$branch = new Branch($conn);
$branchesResult = $branch->getAllBranches();
$branches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);


$selectedBranchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;


if ($_SESSION['role'] === 'branch') {
    $auth = new Auth($conn);
    $userBranchId = $auth->getUserBranch($_SESSION['user_id']);
    $selectedBranchId = $userBranchId;
}


$query = "SELECT si.*, i.item_name, i.item_details, i.unique_code, i.condition_status, i.serial_number, i.warranty_months, i.technical_specs, i.brand, i.model, i.description,
                s.shipment_id, s.shipment_date, s.from_branch_id, s.to_branch_id,
                fb.branch_name as from_branch_name, tb.branch_name as to_branch_name,
                u.username as verified_by_name
         FROM shipment_items si
         JOIN shipments s ON si.shipment_id = s.shipment_id
         JOIN items i ON si.item_id = i.item_id
         LEFT JOIN branches fb ON s.from_branch_id = fb.branch_id
         JOIN branches tb ON s.to_branch_id = tb.branch_id
         LEFT JOIN users u ON si.verified_by = u.user_id
         WHERE si.discrepancy_reported = 1";

if ($selectedBranchId) {
    $query .= " AND s.to_branch_id = :branch_id";
}

$query .= " ORDER BY si.verification_date DESC";

$stmt = $conn->prepare($query);
if ($selectedBranchId) {
    $stmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
}
$stmt->execute();
$discrepancies = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.card { margin-bottom: 20px; }
.table-responsive { margin-top: 20px; }
</style>

<div class="container">
    <h1>Discrepancies</h1>

    <?php if ($_SESSION['role'] !== 'branch'): ?>
    <div class="card">
        <div class="card-header">
            <h5>Filter by Branch</h5>
        </div>
        <div class="card-body">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-4">
                        <select name="branch_id" class="form-control">
                            <option value="">All Branches</option>
                            <?php foreach ($branches as $branch): ?>
                                <option value="<?php echo $branch['branch_id']; ?>" <?php echo ($selectedBranchId == $branch['branch_id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($branch['branch_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary">Filter</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header">
            <h5>Discrepancy Items</h5>
        </div>
        <div class="card-body">
            <?php if (empty($discrepancies)): ?>
                <p>No discrepancies found.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Shipment</th>
                                <th>Branch</th>
                                <th>Shipment Date</th>
                                <th>Discrepancy Recorded</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($discrepancies as $item): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo htmlspecialchars($item['item_name']); ?></strong><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($item['unique_code']); ?></small><br>
                                        Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?><br>
                                        Condition: <?php echo htmlspecialchars($item['condition_status']); ?><br>
                                        Serial: <?php echo htmlspecialchars($item['serial_number'] ?: 'N/A'); ?>
                                    </td>
                                    <td>#<?php echo $item['shipment_id']; ?></td>
                                    <td><?php echo htmlspecialchars($item['to_branch_name']); ?></td>
                                    <td><?php echo date('M d, Y', strtotime($item['shipment_date'])); ?></td>
                                    <td><?php echo date('M d, Y H:i', strtotime($item['verification_date'])); ?><br>
                                        <small>By: <?php echo htmlspecialchars($item['verified_by_name']); ?></small>
                                    </td>
                                    <td><?php echo htmlspecialchars($item['discrepancy_notes']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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