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


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


$auth = new Auth($conn);


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


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


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


$shipment = new Shipment($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']) {
    die("You don't have permission to verify this shipment. Only managers of the destination branch can verify shipments.");
}


if ($shipmentDetails['status'] === 'completed') {
    die("This shipment has already been completed and cannot be modified.");
}

if ($shipmentDetails['status'] === 'rejected') {
    die("This shipment has already been rejected and cannot be modified.");
}


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $success = true;
    $hasDiscrepancy = false;
    $transactionStarted = false;

    try {
        $action = $_POST['action'] ?? 'confirm_selected';
        $postedItems = $_POST['items'] ?? [];

        $conn->beginTransaction();
        $transactionStarted = true;

        if ($action === 'reject_all') {
            $rejectComment = trim($_POST['reject_comment'] ?? '');
            $shipment->rejectShipmentAtReceiving($shipment_id, $_SESSION['user_id'], $rejectComment);
        } else {
            $itemsToProcess = [];
            $processedCount = 0;

            if ($action === 'verify_all') {
                foreach ($shipmentDetails['items'] as $item) {
                    if (empty($item['is_verified'])) {
                        $itemsToProcess[(int)$item['shipment_item_id']] = [
                            'verified' => '1',
                            'notes' => 'Verified using Verify All'
                        ];
                    }
                }
            } else {
                $itemsToProcess = $postedItems;
            }

            if (empty($itemsToProcess)) {
                throw new Exception('Select at least one item to confirm, or use Verify All.');
            }

            foreach ($itemsToProcess as $itemId => $itemData) {
                $shipmentItemId = (int)$itemId;
                $isVerified = isset($itemData['verified']) ? true : false;
                $notes = trim($itemData['notes'] ?? '');
                $reportDiscrepancy = isset($itemData['discrepancy']) ? true : false;
                $discrepancyNotes = trim($itemData['discrepancy_notes'] ?? '');

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

                    $result = $shipment->verifyShipmentItem(
                        $shipmentItemId,
                        $_SESSION['user_id'],
                        $notes,
                        $reportDiscrepancy,
                        $discrepancyNotes
                    );

                    if (!$result) {
                        $success = false;
                        break;
                    }

                    $processedCount++;

                    if ($reportDiscrepancy) {
                        $hasDiscrepancy = true;
                    }
                }
            }

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

        if ($success) {
            $conn->commit();
            $transactionStarted = false;

            if ($action === 'reject_all') {
                $message = '<div class="alert alert-warning">Shipment has been rejected. All items were returned to the sender and the sender was notified.</div>';
            } else {
                $message = '<div class="alert alert-success">Shipment items have been submitted successfully.</div>';
            }


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


            $allVerified = true;
            foreach ($shipmentDetails['items'] as $item) {
                if (!$item['is_verified']) {
                    $allVerified = false;
                    break;
                }
            }

            if ($allVerified) {
                if ($hasDiscrepancy) {
                    $message .= '<div class="alert alert-warning">One or more items have errors. The shipment is paused until those items are confirmed.</div>';
                } else {
                    $message .= '<div class="alert alert-success">All items have been verified and their location has been updated to the destination branch. The shipment has been marked as completed.</div>';
                }
            } elseif ($shipmentDetails['status'] === 'discrepancy') {
                $message .= '<div class="alert alert-warning">The shipment is paused because some items still have reported errors.</div>';
            }
        }
    } catch (Exception $e) {
        if ($transactionStarted) {
            $conn->rollBack();
            $transactionStarted = false;
        }
        $success = false;
        $message = '<div class="alert alert-danger">An error occurred: ' . $e->getMessage() . '</div>';
    }

    if (!$success && $transactionStarted) {
        $conn->rollBack();
        $message = '<div class="alert alert-danger">Failed to verify shipment items. Please try again.</div>';
    }
}


$shipmentDate = new DateTime($shipmentDetails['shipment_date']);
$formattedDate = $shipmentDate->format('F j, Y, g:i a');


$statusClass = '';
switch ($shipmentDetails['status']) {
    case 'pending':
        $statusClass = 'text-warning';
        break;
    case 'shipped':
        $statusClass = 'text-primary';
        break;
    case 'verified':
        $statusClass = 'text-info';
        break;
    case 'completed':
        $statusClass = 'text-success';
        break;
    case 'discrepancy':
        $statusClass = 'text-danger';
        break;
    case 'rejected':
        $statusClass = 'text-danger';
        break;
    default:
        $statusClass = 'text-secondary';
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        .shipment-header {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .status-badge {
            font-size: 1.1em;
            font-weight: bold;
        }
        .verification-form {
            margin-top: 20px;
        }
        .item-card {
            margin-bottom: 15px;
            border-left: 4px solid #007bff;
        }
        .item-card.verified {
            border-left-color: #28a745;
        }
        .item-card.discrepancy {
            border-left-color: #dc3545;
        }
        .discrepancy-notes {
            display: none;
        }
        .verification-actions {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #dee2e6;
        }

        .dashboard-return-link {
            position: relative;
            display: inline-block;
            margin-bottom: 20px;
            margin-left: 20px;
        }

        .verify-all-container {
            float: right;
            margin-bottom: 15px;
            padding: 10px 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }
    </style>
    <a href="view_shipment.php?id=<?php echo $shipment_id; ?>" class="dashboard-return-link">
        <i class="fas fa-arrow-left"></i> Back to Shipment Details
    </a>

    <div class="container mt-4">
        <h2>Verify Shipment #<?php echo $shipment_id; ?></h2>

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

        <div class="shipment-header">
            <div class="row">
                <div class="col-md-6">
                    <p><strong>From:</strong> <?php echo $shipmentDetails['from_branch_name'] ?: 'Headquarters'; ?></p>
                    <p><strong>To:</strong> <?php echo htmlspecialchars($shipmentDetails['to_branch_name']); ?></p>
                    <p><strong>Created By:</strong> <?php echo htmlspecialchars($shipmentDetails['created_by_name']); ?></p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p><strong>Date:</strong> <?php echo $formattedDate; ?></p>
                    <p><strong>Status:</strong> <span class="status-badge <?php echo $statusClass; ?>"><?php echo ucfirst($shipmentDetails['status']); ?></span></p>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Verify Shipment Items</h5>
            </div>
            <div class="card-body">
                <p class="text-muted">Verify each received item before confirming the shipment. If an item has an error, report it with a comment; the shipment will pause and notify the sender until the item is corrected and confirmed.</p>

                <form method="post" action="" class="verification-form">
                    <?php if (count(array_filter($shipmentDetails['items'], function($item) { return !$item['is_verified']; })) > 0): ?>
                    <div class="verify-all-container">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="verify-all-items">
                            <label class="form-check-label" for="verify-all-items">
                                <strong>Verify All Items</strong> - Check all unverified items at once
                            </label>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php foreach ($shipmentDetails['items'] as $item): ?>
                        <div class="card item-card <?php echo $item['is_verified'] ? ($item['discrepancy_reported'] ? 'discrepancy' : 'verified') : ''; ?>">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h5><?php echo htmlspecialchars($item['item_name']); ?></h5>
                                        <p><strong>Details:</strong> <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></p>
                                        <p><strong>Code:</strong> <?php echo htmlspecialchars($item['unique_code']); ?></p>
                                        <p><strong>Unit Price:</strong> <?php echo htmlspecialchars($item['unit_price']); ?></p>
                                        <p><strong>Quantity:</strong> <?php echo htmlspecialchars($item['quantity']); ?></p>
                                    </div>
                                    <div class="col-md-6">
                                        <?php if ($item['is_verified']): ?>
                                            <div class="alert alert-success">
                                                <strong>Verified</strong> by <?php echo htmlspecialchars($item['verified_by_name']); ?> on <?php echo (new DateTime($item['verification_date']))->format('M j, Y, g:i a'); ?>
                                            </div>
                                            <?php if (!empty($item['verification_notes'])): ?>
                                                <p><strong>Notes:</strong> <?php echo htmlspecialchars($item['verification_notes']); ?></p>
                                            <?php endif; ?>

                                            <?php if ($item['discrepancy_reported']): ?>
                                                <div class="alert alert-danger">
                                                    <strong>Discrepancy Reported:</strong> <?php echo htmlspecialchars($item['discrepancy_notes']); ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <?php if ($item['discrepancy_reported']): ?>
                                                <div class="alert alert-warning">
                                                    <strong>Paused for correction:</strong> <?php echo htmlspecialchars($item['discrepancy_notes']); ?>
                                                </div>
                                            <?php endif; ?>

                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="checkbox" name="items[<?php echo $item['shipment_item_id']; ?>][verified]" id="verify-<?php echo $item['shipment_item_id']; ?>" value="1">
                                                <label class="form-check-label" for="verify-<?php echo $item['shipment_item_id']; ?>">
                                                    <strong>Verify this item</strong> - I confirm that this item has been received
                                                </label>
                                            </div>

                                            <div class="mb-3">
                                                <label for="notes-<?php echo $item['shipment_item_id']; ?>" class="form-label">Verification Notes (optional):</label>
                                                <textarea class="form-control" name="items[<?php echo $item['shipment_item_id']; ?>][notes]" id="notes-<?php echo $item['shipment_item_id']; ?>" rows="2"></textarea>
                                            </div>

                                            <div class="form-check mb-3">
                                                <input class="form-check-input discrepancy-check" type="checkbox" name="items[<?php echo $item['shipment_item_id']; ?>][discrepancy]" id="discrepancy-<?php echo $item['shipment_item_id']; ?>" value="1">
                                                <label class="form-check-label" for="discrepancy-<?php echo $item['shipment_item_id']; ?>">
                                                    <strong>Report Discrepancy</strong> - There is an issue with this item
                                                </label>
                                            </div>

                                            <div class="mb-3 discrepancy-notes" id="discrepancy-notes-<?php echo $item['shipment_item_id']; ?>">
                                                <label for="discrepancy-notes-text-<?php echo $item['shipment_item_id']; ?>" class="form-label">Discrepancy Details:</label>
                                                <textarea class="form-control" name="items[<?php echo $item['shipment_item_id']; ?>][discrepancy_notes]" id="discrepancy-notes-text-<?php echo $item['shipment_item_id']; ?>" rows="2"><?php echo htmlspecialchars($item['discrepancy_notes'] ?? ''); ?></textarea>
                                                <small class="text-muted">Please describe the issue (e.g., missing items, damaged goods, incorrect quantity)</small>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <div class="verification-actions">
                        <div class="mb-3">
                            <label for="reject-comment" class="form-label">Reject All Comment</label>
                            <textarea class="form-control" name="reject_comment" id="reject-comment" rows="2" placeholder="Required only when rejecting the whole shipment"></textarea>
                        </div>
                        <button type="submit" name="action" value="confirm_selected" class="btn btn-primary btn-lg">
                            <i class="fas fa-check-circle"></i> Confirm Selected
                        </button>
                        <button type="submit" name="action" value="verify_all" class="btn btn-success btn-lg me-2">
                            <i class="fas fa-check-double"></i> Verify All & Confirm
                        </button>
                        <button type="submit" name="action" value="reject_all" class="btn btn-danger btn-lg me-2">
                            <i class="fas fa-ban"></i> Discard All & Reject
                        </button>
                        <a href="view_shipment.php?id=<?php echo $shipment_id; ?>" class="btn btn-outline-secondary btn-lg me-2">
                            <i class="fas fa-times-circle"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {

            $('.discrepancy-check').change(function() {
                var itemId = $(this).attr('id').replace('discrepancy-', '');
                if($(this).is(':checked')) {
                    $('#discrepancy-notes-' + itemId).show();
                } else {
                    $('#discrepancy-notes-' + itemId).hide();
                }
            });


            $('#verify-all-items').change(function() {
                var isChecked = $(this).is(':checked');

                $('.form-check-input').each(function() {
                    var id = $(this).attr('id');
                    if (id && id.startsWith('verify-') && id !== 'verify-all-items') {
                        $(this).prop('checked', isChecked);
                    }
                });
            });


            $('form.verification-form').submit(function(e) {
                var action = $(document.activeElement).val();
                if (action === 'reject_all') {
                    if ($('#reject-comment').val().trim() === '') {
                        alert('Please write a comment before rejecting the shipment.');
                        $('#reject-comment').focus();
                        return false;
                    }
                    return confirm('Reject the entire shipment and return all items to the sender?');
                }

                var valid = true;
                $('.discrepancy-check:checked').each(function() {
                    var itemId = $(this).attr('id').replace('discrepancy-', '');
                    var notes = $('#discrepancy-notes-text-' + itemId).val().trim();
                    if(notes === '') {
                        alert('Please provide details for all reported discrepancies.');
                        $('#discrepancy-notes-text-' + itemId).focus();
                        valid = false;
                        return false;
                    }
                });

                return valid;
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
