<?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'], ['admin', 'super_admin'])) {
    header('Location: /unauthorized.php');
    exit();
}


$shipmentId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$shipmentId) {
    header('Location: pending_approvals.php');
    exit();
}


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


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


if (!$shipmentDetails) {
    $_SESSION['error'] = 'Shipment not found.';
    header('Location: pending_approvals.php');
    exit();
}

$canApprove = in_array($shipmentDetails['status'], ['pending']);
$isApproved = $shipmentDetails['status'] === 'shipped';

?>

<style>
.badge {
    font-size: 0.75em;
}


.approval-form {
    pointer-events: all !important;
}

.approval-form button {
    pointer-events: all !important;
    cursor: pointer !important;
}
</style>

<script>

document.addEventListener('DOMContentLoaded', function() {
    console.log('Setting up approval form handlers');


    const approveForm = document.getElementById('approveForm');
    const rejectForm = document.getElementById('rejectForm');

    if (approveForm) {

        approveForm.addEventListener('submit', function(e) {
            console.log('Approve form submitting');

        });


        const approveButton = document.getElementById('approveButton');
        if (approveButton) {
            approveButton.addEventListener('click', function(e) {
                console.log('Approve button clicked');
                if (confirm('Are you sure you want to approve this shipment? This will make it available for the destination branch to receive.')) {
                    console.log('User confirmed approval');

                } else {
                    e.preventDefault();
                }
            });
        }
    }

    if (rejectForm) {
        rejectForm.addEventListener('submit', function(e) {
            console.log('Reject form submitting');

        });
    }


    const allForms = document.querySelectorAll('form');
    console.log('All forms found:', allForms.length);
    allForms.forEach((form, index) => {
        console.log(`Form ${index}:`, form.className, form.id);
    });
});
</script>

<div class="dashboard-container">
    <div class="main-content">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>Review Shipment #<?php echo htmlspecialchars($shipmentId); ?></h1>
                <a href="pending_approvals.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to List
                </a>
            </div>

            <?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="row">
                <div class="col-md-8">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>Shipment Details</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Status:</strong>
                                        <?php
                                        $statusClass = '';
                                        $statusText = ucfirst($shipmentDetails['status']);
                                        switch($shipmentDetails['status']) {
                                            case 'pending':
                                                $statusClass = 'bg-warning text-dark';
                                                break;
                                            case 'shipped':
                                                $statusClass = 'bg-success';
                                                $statusText = 'Approved';
                                                break;
                                            case 'rejected':
                                                $statusClass = 'bg-danger';
                                                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>
                                    </p>
                                    <p><strong>From:</strong> <?php echo htmlspecialchars($shipmentDetails['from_branch_name'] ?? 'Headquarters'); ?></p>
                                    <p><strong>To:</strong> <?php echo htmlspecialchars($shipmentDetails['to_branch_name']); ?></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Created On:</strong> <?php echo htmlspecialchars(date('Y-m-d H:i:s', strtotime($shipmentDetails['shipment_date']))); ?></p>
                                    <p><strong>Created By:</strong> <?php echo htmlspecialchars($shipmentDetails['created_by_name']); ?></p>
                                    <p><strong>Total Items:</strong> <span class="badge bg-info"><?php echo count($shipmentDetails['items']); ?></span></p>
                                </div>
                            </div>

                            <?php if ($isApproved): ?>
                                <div class="alert alert-info mt-3">
                                    <i class="fas fa-info-circle"></i>
                                    <strong>Status Update:</strong> This shipment has been approved and is ready for dispatch to <strong><?php echo htmlspecialchars($shipmentDetails['to_branch_name']); ?></strong>.
                                    The destination branch can now receive and verify the items.
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <?php if ($canApprove): ?>
                <div class="col-md-4">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>Approval Actions</h5>
                        </div>
                        <div class="card-body">

                            <div class="alert alert-info mb-3">
                                <strong>Debug Info:</strong><br>
                                Status: <?php echo $shipmentDetails['status']; ?><br>
                                Can Approve: <?php echo $canApprove ? 'Yes' : 'No'; ?><br>
                                User Role: <?php echo $_SESSION['role']; ?><br>
                                User ID: <?php echo $_SESSION['user_id']; ?><br>
                                Created By: <?php echo $shipmentDetails['created_by']; ?>
                            </div>

                            <form action="../../views/shipments/approve_shipment.php" method="POST" class="approval-form no-ajax" id="approveForm">
                                <input type="hidden" name="shipment_id" value="<?php echo htmlspecialchars($shipmentId); ?>">
                                <button type="submit" name="approve" class="btn btn-success w-100 mb-3" id="approveButton">
                                    <i class="fas fa-check"></i> Approve Shipment
                                </button>
                            </form>

                            <hr>

                            <form action="../../views/shipments/approve_shipment.php" method="POST" class="approval-form no-ajax" id="rejectForm" onsubmit="return confirm('Are you sure you want to reject this shipment? Items will be returned to the source branch.');">
                                <input type="hidden" name="shipment_id" value="<?php echo htmlspecialchars($shipmentId); ?>">
                                <div class="mb-3">
                                    <label for="rejection_notes" class="form-label">Reason for Rejection <span class="text-danger">*</span></label>
                                    <textarea name="rejection_notes" id="rejection_notes" class="form-control" rows="3" required placeholder="Please provide a detailed reason for rejection..."></textarea>
                                </div>
                                <button type="submit" name="reject" class="btn btn-danger w-100">
                                    <i class="fas fa-times"></i> Reject Shipment
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>


            <div class="card">
                <div class="card-header">
                    <h5>Items in Shipment (<?php echo count($shipmentDetails['items']); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($shipmentDetails['items'])): ?>
                        <p class="text-center text-muted">No items found in this shipment.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Item Code</th>
                                        <th>Item Name</th>
                                        <th>Item Details</th>
                                        <th>Unit Price (MWK)</th>
                                        <th>Condition</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($shipmentDetails['items'] as $index => $item): ?>
                                        <tr>
                                            <td><?php echo $index + 1; ?></td>
                                            <td><code><?php echo htmlspecialchars($item['unique_code']); ?></code></td>
                                            <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                                            <td><?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></td>
                                            <td><?php echo number_format(htmlspecialchars($item['unit_price']), 2); ?></td>
                                            <td>
                                                <span class="badge bg-secondary">
                                                    <?php echo htmlspecialchars($item['condition_status'] ?? 'Good'); ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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