<?php

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


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


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);


if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("No shipment selected.");
}
$shipment_id = (int)$_GET['id'];


$shipment = new Shipment($conn, $logger);
$branchModel = new Branch($conn, $logger);


$shipmentDetails = $shipment->getShipmentDetails($shipment_id);

if (!$shipmentDetails) {
    die("Shipment not found.");
}


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

if (!$isSuperAdmin && $userBranchId != $shipmentDetails['to_branch_id'] && $userBranchId != $shipmentDetails['from_branch_id']) {
    die("You don't have permission to view this shipment.");
}


$canVerify = $isSuperAdmin || $userBranchId == $shipmentDetails['to_branch_id'];
$canDeletePending = $shipmentDetails['status'] === 'pending'
    && ($isSuperAdmin || $auth->isWarehousePersonnel($_SESSION['user_id']) || ($_SESSION['role'] === 'branch' && $userBranchId == $shipmentDetails['from_branch_id']));
$settings = Branding::settings();
$currencyCode = $settings['currency_code'] ?? 'MWK';
$fromBranch = !empty($shipmentDetails['from_branch_id']) ? $branchModel->getBranchById($shipmentDetails['from_branch_id']) : null;
$toBranch = $branchModel->getBranchById($shipmentDetails['to_branch_id']);
$shipmentBranding = Branding::documentDetailsForBranch($fromBranch ?: $toBranch ?: []);
$shipmentItemsTotal = 0;
foreach ($shipmentDetails['items'] as $item) {
    $shipmentItemsTotal += (float)($item['unit_price'] ?? 0);
}


$isCompleted = $shipmentDetails['status'] === 'completed';
$isRejected = $shipmentDetails['status'] === 'rejected';


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canVerify && !$isCompleted && !$isRejected) {
    $transactionStarted = false;
    try {
        $conn->beginTransaction();
        $transactionStarted = true;

        $processedCount = 0;
        foreach (($_POST['items'] ?? []) as $shipmentItemId => $itemData) {
            $hasDiscrepancy = isset($itemData['discrepancy']);
            $discrepancyNotes = trim($itemData['discrepancy_notes'] ?? '');

            if ($hasDiscrepancy && $discrepancyNotes === '') {
                throw new Exception('Please provide a comment for every item with an error.');
            }

            if (isset($itemData['verified']) || $hasDiscrepancy) {
                $shipment->verifyShipmentItem(
                    (int)$shipmentItemId,
                    $_SESSION['user_id'],
                    trim($itemData['notes'] ?? ''),
                    $hasDiscrepancy,
                    $discrepancyNotes
                );
                $processedCount++;
            }
        }

        if ($processedCount === 0) {
            throw new Exception('Select at least one item to confirm or report an item error.');
        }

        $conn->commit();
        $message = '<div class="alert alert-success">Shipment items verified successfully.</div>';


        $shipmentDetails = $shipment->getShipmentDetails($shipment_id);
        $isCompleted = $shipmentDetails['status'] === 'completed';
        $isRejected = $shipmentDetails['status'] === 'rejected';

    } catch (Exception $e) {
        if ($transactionStarted) {
            $conn->rollBack();
        }
        $message = '<div class="alert alert-danger">An error occurred: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}


function formatDate($dateStr) {
    if (empty($dateStr)) return 'N/A';
    return (new DateTime($dateStr))->format('F j, Y H:i');
}

function contactValue($branch, $key) {
    return trim((string)($branch[$key] ?? '')) ?: 'N/A';
}


$statusClass = [
    'pending' => 'text-warning',
    'shipped' => 'text-primary',
    'verified' => 'text-info',
    'completed' => 'text-success',
    'discrepancy' => 'text-danger',
    'rejected' => 'text-danger',
][$shipmentDetails['status']] ?? 'text-secondary';
?>

<style>
    .shipment-header { background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
    .status-badge { font-size: 1.1em; font-weight: bold; }
    .item-card { margin-bottom: 1.5rem; border: 1px solid #dee2e6; border-radius: .25rem; }
    .item-card-header { background-color: #f8f9fa; padding: 1rem; border-bottom: 1px solid #dee2e6; }
    .item-card-body { padding: 1rem; }
    .item-details-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; }
    .detail-item { background-color: #f8f9fa; padding: 8px; border-radius: 4px; }
    .detail-item strong { display: block; color: #495057; }
    .verified-overlay { background-color: rgba(40, 167, 69, 0.1); border-left: 5px solid #28a745; }
    .discrepancy-overlay { background-color: rgba(220, 53, 69, 0.1); border-left: 5px solid #dc3545; }
    .discrepancy-notes { display: none; }
    .verification-actions { margin-top: 20px; padding-top: 20px; border-top: 1px solid #dee2e6; }
    .verify-all-container { float: right; margin-bottom: 15px; }
    .shipment-document { background: #fff; border: 1px solid #d6dbe1; margin-bottom: 24px; }
    .shipment-document-header { display: flex; justify-content: space-between; gap: 24px; padding: 24px; border-bottom: 2px solid #343a40; }
    .shipment-brand { display: flex; gap: 16px; align-items: center; }
    .shipment-brand img { max-height: 70px; max-width: 150px; object-fit: contain; }
    .shipment-brand h1 { font-size: 22px; margin: 0; text-transform: uppercase; letter-spacing: 1px; }
    .document-title { text-align: right; }
    .document-title h2 { font-size: 20px; margin: 0; }
    .document-title p { margin: 4px 0 0; color: #6c757d; }
    .shipment-document-body { padding: 24px; }
    .document-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 20px; }
    .document-panel { border: 1px solid #e1e5ea; padding: 14px; min-height: 120px; }
    .document-panel h3 { font-size: 13px; margin: 0 0 10px; text-transform: uppercase; color: #495057; letter-spacing: .5px; }
    .document-panel p { margin: 0 0 5px; }
    .summary-strip { display: grid; grid-template-columns: repeat(4, 1fr); border: 1px solid #e1e5ea; margin-bottom: 20px; }
    .summary-strip div { padding: 12px; border-right: 1px solid #e1e5ea; }
    .summary-strip div:last-child { border-right: 0; }
    .summary-strip strong { display: block; color: #495057; font-size: 12px; text-transform: uppercase; }
    .shipment-document table { width: 100%; border-collapse: collapse; }
    .shipment-document th, .shipment-document td { border: 1px solid #e1e5ea; padding: 8px; font-size: 13px; vertical-align: top; }
    .shipment-document th { background: #f8f9fa; text-transform: uppercase; font-size: 12px; }
    .document-footer { display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; padding-top: 30px; }
    .signature-line { border-top: 1px solid #343a40; padding-top: 6px; text-align: center; color: #495057; }
    @media print {
        .no-print, .verification-form, .verification-actions, .navbar, script { display: none !important; }
        body { background: #fff; }
        .container { max-width: none; width: 100%; }
        .shipment-document { border: 0; }
    }
</style> 

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-3 no-print">
        <h2>Shipment #<?php echo $shipment_id; ?> Details</h2>
        <div>
            <a href="../inventory/verify.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Back to Shipments</a>
            <button onclick="window.print()" class="btn btn-outline-secondary"><i class="fas fa-print"></i> Print</button>
            <?php if ($canVerify && !$isCompleted && !$isRejected): ?>
                <a href="verify_shipment.php?id=<?php echo (int)$shipment_id; ?>" class="btn btn-primary"><i class="fas fa-check-circle"></i> Verify / Confirm</a>
            <?php endif; ?>
            <?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_id; ?>">
                    <input type="hidden" name="redirect_to" value="view_shipments.php?branch_id=<?php echo (int)$shipmentDetails['from_branch_id']; ?>&type=all&status=pending">
                    <button type="submit" class="btn btn-outline-danger"><i class="fas fa-trash"></i> Delete Pending Shipment</button>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <?php if (!empty($message)) echo $message; ?>

    <section class="shipment-document">
        <div class="shipment-document-header">
            <div class="shipment-brand">
                <img src="<?php echo htmlspecialchars($shipmentBranding['logo']); ?>" alt="<?php echo htmlspecialchars($shipmentBranding['name']); ?> Logo">
                <div>
                    <h1><?php echo htmlspecialchars($shipmentBranding['name']); ?></h1>
                </div>
            </div>
            <div class="document-title">
                <h2>Shipment Document</h2>
                <p>Shipment #<?php echo (int)$shipment_id; ?></p>
                <p>Printed: <?php echo htmlspecialchars(date('F j, Y H:i')); ?></p>
            </div>
        </div>

        <div class="shipment-document-body">
            <div class="document-grid">
                <div class="document-panel">
                    <h3>From Branch</h3>
                    <p><strong><?php echo htmlspecialchars($shipmentDetails['from_branch_name'] ?? 'Headquarters'); ?></strong></p>
                    <p><?php echo nl2br(htmlspecialchars(contactValue($fromBranch, 'branch_address'))); ?></p>
                    <p>Phone: <?php echo htmlspecialchars(contactValue($fromBranch, 'branch_phone')); ?></p>
                    <p>Email: <?php echo htmlspecialchars(contactValue($fromBranch, 'branch_email')); ?></p>
                    <p>Website: <?php echo htmlspecialchars(contactValue($fromBranch, 'branch_website')); ?></p>
                </div>
                <div class="document-panel">
                    <h3>To Branch</h3>
                    <p><strong><?php echo htmlspecialchars($shipmentDetails['to_branch_name']); ?></strong></p>
                    <p><?php echo nl2br(htmlspecialchars(contactValue($toBranch, 'branch_address'))); ?></p>
                    <p>Phone: <?php echo htmlspecialchars(contactValue($toBranch, 'branch_phone')); ?></p>
                    <p>Email: <?php echo htmlspecialchars(contactValue($toBranch, 'branch_email')); ?></p>
                    <p>Website: <?php echo htmlspecialchars(contactValue($toBranch, 'branch_website')); ?></p>
                </div>
                <div class="document-panel">
                    <h3>Shipment Information</h3>
                    <p><strong>Status:</strong> <span class="<?php echo $statusClass; ?>"><?php echo htmlspecialchars(ucfirst($shipmentDetails['status'])); ?></span></p>
                    <p><strong>Created By:</strong> <?php echo htmlspecialchars($shipmentDetails['created_by_name'] ?? 'N/A'); ?></p>
                    <p><strong>Shipment Date:</strong> <?php echo htmlspecialchars(formatDate($shipmentDetails['shipment_date'] ?? $shipmentDetails['created_at'] ?? null)); ?></p>
                    <p><strong>Approved By:</strong> <?php echo htmlspecialchars($shipmentDetails['approved_by_name'] ?? 'N/A'); ?></p>
                    <p><strong>Approved Date:</strong> <?php echo htmlspecialchars(formatDate($shipmentDetails['approved_at'] ?? null)); ?></p>
                </div>
            </div>

            <div class="summary-strip">
                <div><strong>Items</strong><?php echo count($shipmentDetails['items']); ?></div>
                <div><strong>Total Value</strong><?php echo htmlspecialchars($currencyCode); ?> <?php echo number_format($shipmentItemsTotal, 2); ?></div>
                <div><strong>Verified</strong><?php echo count(array_filter($shipmentDetails['items'], function($item) { return !empty($item['is_verified']); })); ?></div>
                <div><strong>Discrepancies</strong><?php echo count(array_filter($shipmentDetails['items'], function($item) { return !empty($item['discrepancy_reported']); })); ?></div>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Code</th>
                        <th>Item</th>
                        <th>Item Details</th>
                        <th>Brand / Model</th>
                        <th>Serial</th>
                        <th>Condition</th>
                        <th>Unit Value</th>
                        <th>Verification</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($shipmentDetails['items'] as $index => $item): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo htmlspecialchars($item['unique_code']); ?></td>
                            <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                            <td><?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars(trim(($item['brand'] ?? '') . ' ' . ($item['model'] ?? '')) ?: 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($item['serial_number'] ?: 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($item['condition_status'] ?: 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($currencyCode); ?> <?php echo number_format((float)$item['unit_price'], 2); ?></td>
                            <td>
                                <?php if ($item['is_verified']): ?>
                                    <?php echo $item['discrepancy_reported'] ? 'Discrepancy' : 'Verified'; ?>
                                <?php else: ?>
                                    Pending
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>in

            <div class="document-footer">
                <div class="signature-line">Prepared By</div>
                <div class="signature-line">Dispatched By</div>
                <div class="signature-line">Received By</div>
            </div>
        </div>
    </section>
</div>

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