<?php



require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Tracking.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';


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


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


$auth = new Auth($conn);
$tracking = new Tracking($conn);


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id']) &&
    !$auth->isSalesAssistant($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}


if ($auth->isSuperAdmin($_SESSION['user_id'])) {
    $userRole = 'admin';
} elseif ($auth->isWarehousePersonnel($_SESSION['user_id'])) {
    $userRole = 'warehouse';
} elseif ($auth->isBranchManager($_SESSION['user_id']) || $auth->isSalesAssistant($_SESSION['user_id'])) {
    $userRole = 'branch_manager';
} else {
    $userRole = 'admin';
}


if (!function_exists('getDashboardLink')) {
    function getDashboardLink() {
        if (isset($_SESSION['role'])) {
            switch ($_SESSION['role']) {
                case 'admin':
                case 'super_admin':
                    return '../dashboard/admin.php';
                case 'warehouse':
                case 'branch_manager':
                case 'warehouse_personnel':
                    return '../dashboard/branch.php';
                case 'sales':
                case 'sales_assistant':
                    return '../dashboard/assistant.php';
                case 'branch':
                default:
                    return '../dashboard/branch.php';
            }
        }
        return '../dashboard/branch.php';
    }
}


$itemData = [];
$transactionData = [];
$error = '';
$success = '';

if (isset($_GET['transaction_id']) && trim($_GET['transaction_id']) !== '') {
    $transactionId = trim($_GET['transaction_id']);
    $transactionData = $tracking->getTransactionInfoWithAccessControl($transactionId, $_SESSION['user_id'], $userRole);

    if (isset($transactionData['error'])) {
        $error = $transactionData['error'];
    } else {
        $success = 'Transaction preview retrieved successfully.';
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['transaction_id']) && trim($_POST['transaction_id']) !== '') {
    $transactionId = trim($_POST['transaction_id']);
    $transactionData = $tracking->getTransactionInfoWithAccessControl($transactionId, $_SESSION['user_id'], $userRole);

    if (isset($transactionData['error'])) {
        $error = $transactionData['error'];
    } else {
        $success = 'Transaction preview retrieved successfully.';
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['unique_code'])) {
    $uniqueCode = trim($_POST['unique_code']);

    if (empty($uniqueCode)) {
        $error = 'Please enter a unique code.';
    } else {

        $itemData = $tracking->getItemInfoAndHistoryWithAccessControl($uniqueCode, $_SESSION['user_id'], $userRole);

        if (isset($itemData['error'])) {
            $error = $itemData['error'];
        } else {
            $success = 'Item information and tracking history retrieved successfully.';
        }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <div class="container mt-5">
        <a href="<?php echo getDashboardLink(); ?>" class="btn btn-secondary mb-3">Back to Dashboard</a>

<style>

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Roboto', sans-serif;
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        background-color: #f8f9fa;
    }

    .container {
        width: 100%;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px;
    }


    .dashboard-container {
        display: flex;
        width: 100%;
        margin-top: 20px;
    }


    .sidebar {
        width: 250px;
        background-color: #343a40;
        color: white;
        padding: 20px;
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        overflow-y: auto;
        z-index: 100;
    }

    .sidebar-heading {
        padding: 10px 0;
        font-size: 18px;
        font-weight: 500;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        margin-bottom: 15px;
    }

    .sidebar-menu {
        list-style: none;
        padding: 0;
        margin: 0 0 25px 0;
    }

    .sidebar-menu li {
        margin-bottom: 5px;
    }

    .sidebar-menu a {
        display: block;
        padding: 10px 15px;
        color: rgba(255,255,255,0.8);
        text-decoration: none;
        transition: all 0.3s;
        border-radius: 4px;
    }

    .sidebar-menu a:hover, .sidebar-menu a.active {
        background-color: rgba(255,255,255,0.1);
        color: white;
    }

    .sidebar-menu i {
        margin-right: 10px;
        width: 20px;
        text-align: center;
    }

    .sidebar-section {
        margin-bottom: 25px;
    }


    .main-content {
        flex: 1;
        margin-left: 250px;
        padding: 20px;
        width: calc(100% - 250px);
    }


    .card {
        background-color: white;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        width: 100%;
    }

    .card-header {
        padding: 15px 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .card-header h2, .card-header h5 {
        margin: 0;
        font-size: 1.2rem;
    }

    .card-body {
        padding: 20px;
    }


    .timeline {
        position: relative;
        padding: 20px 0;
    }

    .timeline::before {
        content: '';
        position: absolute;
        left: 30px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #dee2e6;
    }

    .timeline-item {
        position: relative;
        margin-left: 60px;
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 5px;
        border-left: 4px solid #007bff;
    }

    .timeline-item::before {
        content: '';
        position: absolute;
        left: -38px;
        top: 20px;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background: #007bff;
        border: 2px solid #fff;
    }

    .timeline-item.added {
        border-left-color: #28a745;
    }

    .timeline-item.added::before {
        background: #28a745;
    }

    .timeline-item.shipped {
        border-left-color: #ffc107;
    }

    .timeline-item.shipped::before {
        background: #ffc107;
    }

    .timeline-item.received {
        border-left-color: #17a2b8;
    }

    .timeline-item.received::before {
        background: #17a2b8;
    }

    .timeline-item.sold {
        border-left-color: #dc3545;
    }

    .timeline-item.sold::before {
        background: #dc3545;
    }

    .timeline-date {
        font-size: 0.9rem;
        color: #6c757d;
        margin-bottom: 5px;
    }

    .timeline-title {
        font-weight: bold;
        margin-bottom: 5px;
    }

    .timeline-details {
        font-size: 0.9rem;
        color: #495057;
    }


    .alert {
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid transparent;
        border-radius: 4px;
    }

    .alert-success {
        color: #155724;
        background-color: #d4edda;
        border-color: #c3e6cb;
    }

    .alert-danger {
        color: #721c24;
        background-color: #f8d7da;
        border-color: #f5c6cb;
    }


    .form-group {
        margin-bottom: 15px;
    }

    .form-label {
        display: block;
        margin-bottom: 5px;
        font-weight: 500;
    }

    .form-control {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ced4da;
        border-radius: 4px;
        font-size: 14px;
    }

    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        text-decoration: none;
        display: inline-block;
    }

    .btn-primary {
        background-color: #007bff;
        color: white;
    }

    .btn-primary:hover {
        background-color: #0056b3;
    }


    footer {
        margin-left: 250px;
        background-color: #f8f9fa;
        text-align: center;
        padding: 15px 0;
        border-top: 1px solid #eee;
        width: calc(100% - 250px);
    }


    @media (max-width: 768px) {
        .sidebar {
            width: 200px;
        }
        .main-content, footer {
            margin-left: 200px;
            width: calc(100% - 200px);
        }
    }
</style>

        <div class="container">
            <h1 class="mb-4">Receipt Tracking </h1>
            <?php if ($userRole === 'branch_manager'): ?>
                <p class="text-muted">Track items that have been shipped to your branch</p>
            <?php elseif ($userRole === 'warehouse'): ?>
                <p class="text-muted">Track item lifecycle and manage warehouse inventory</p>
            <?php else: ?>
                <p class="text-muted">Track transaction </p>
            <?php endif; ?>

            <div class="card">
                <div class="card-header">
                    <h5>Track receipt by transaction number </h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                        <div class="form-group">
                            <label for="transaction_id" class="form-label">Enter transaction id:</label>
                            <input type="text"
                                   class="form-control"
                                   id="transaction_id"
                                   name="transaction_id"
                                   placeholder="e.g., TXN-65f2a1b9c3d4e"
                                   value="<?php echo htmlspecialchars($_POST['transaction_id'] ?? $_GET['transaction_id'] ?? ''); ?>"
                                   required>
                        </div>
                        <button type="submit" class="btn btn-primary">Preview Transaction</button>
                    </form>
                </div>
            </div>

            <?php if (!empty($error)): ?>
                <div class="alert alert-danger">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success)): ?>
                <div class="alert alert-success">
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($transactionData) && !isset($transactionData['error'])): ?>
                <div class="card">
                    <div class="card-header">
                        <h5>Transaction Preview</h5>
                    </div>
                    <div class="card-body">
                        <?php $transactionInfo = $transactionData['transaction_info']; ?>
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Transaction ID:</strong> <?php echo htmlspecialchars($transactionInfo['transaction_id']); ?></p>
                                <p><strong>Branch:</strong> <?php echo htmlspecialchars($transactionInfo['branch_name'] ?? 'Unknown'); ?></p>
                                <p><strong>Sold By:</strong> <?php echo htmlspecialchars($transactionInfo['sold_by_name'] ?? 'Unknown'); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Date:</strong> <?php echo date('M d, Y H:i:s', strtotime($transactionInfo['sold_at'])); ?></p>
                                <p><strong>Customer:</strong> <?php echo htmlspecialchars($transactionInfo['customer_name'] ?: 'N/A'); ?></p>
                                <p><strong>Phone:</strong> <?php echo htmlspecialchars($transactionInfo['customer_phone'] ?: 'N/A'); ?></p>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Item Details</th>
                                        <th>Code</th>
                                        <th>Unit Price</th>
                                        <th>Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactionData['items'] as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown item'); ?></td>
                                            <td><?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($item['unique_code']); ?></td>
                                            <td>MWK <?php echo number_format((float)$item['unit_price'], 2); ?></td>
                                            <td>MWK <?php echo number_format((float)$item['total_price'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="4" class="text-end">Total</th>
                                        <th>MWK <?php echo number_format((float)$transactionInfo['total_amount'], 2); ?></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if (!empty($itemData) && !isset($itemData['error'])): ?>
                <div class="card">
                    <div class="card-header">
                        <h5>Item Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Item Name:</strong> <?php echo htmlspecialchars($itemData['item_info']['item_name']); ?></p>
                                <p><strong>Item Details:</strong> <?php echo htmlspecialchars($itemData['item_info']['item_details'] ?? 'N/A'); ?></p>
                                <p><strong>Unique Code:</strong> <?php echo htmlspecialchars($itemData['item_info']['unique_code']); ?></p>
                                <p><strong>Unit Price:</strong> MWK <?php echo number_format($itemData['item_info']['unit_price'], 2); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Current Location:</strong> <?php echo htmlspecialchars($itemData['item_info']['current_location_name'] ?? 'Unknown'); ?></p>
                                <p><strong>Condition:</strong> <?php echo htmlspecialchars($itemData['item_info']['condition_status']); ?></p>
                                <p><strong>Created:</strong> <?php echo date('M d, Y H:i:s', strtotime($itemData['item_info']['created_at'])); ?></p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h5>Item Lifecycle History</h5>
                    </div>
                    <div class="card-body">
                        <div class="timeline">
                            <?php foreach ($itemData['tracking_history'] as $event): ?>
                                <div class="timeline-item <?php echo htmlspecialchars($event['event_type']); ?>">
                                    <div class="timeline-date">
                                        <?php echo date('M d, Y H:i:s', strtotime($event['event_date'])); ?>
                                    </div>
                                    <div class="timeline-title">
                                        <?php
                                        switch ($event['event_type']) {
                                            case 'added':
                                                echo '📦 Item Added to Warehouse';
                                                break;
                                            case 'shipped':
                                                echo '🚚 Item Shipped from Warehouse';
                                                break;
                                            case 'received':
                                                echo '📥 Item Received at Branch - ' . htmlspecialchars($event['branch_name']);
                                                break;
                                            case 'sold':
                                                echo '💰 Item Sold at Branch';
                                                break;
                                            default:
                                                echo ucfirst($event['event_type']);
                                        }
                                        ?>
                                    </div>
                                    <div class="timeline-details">
                                        <?php if ($event['event_type'] === 'received'): ?>
                                            <strong>📅 Received Date:</strong> <?php echo date('M d, Y \a\t H:i:s', strtotime($event['event_date'])); ?><br>
                                            <strong>🏢 Branch:</strong> <?php echo htmlspecialchars($event['branch_name']); ?><br>
                                            <?php if ($event['performed_by']): ?>
                                                <strong>👤 Verified by:</strong> <?php echo htmlspecialchars($event['performed_by']); ?><br>
                                            <?php endif; ?>
                                        <?php elseif ($event['event_type'] === 'shipped'): ?>
                                            <strong>📅 Shipped Date:</strong> <?php echo date('M d, Y \a\t H:i:s', strtotime($event['event_date'])); ?><br>
                                            <strong>🏭 From:</strong> Warehouse<br>
                                            <?php if ($event['performed_by']): ?>
                                                <strong>👤 Shipped by:</strong> <?php echo htmlspecialchars($event['performed_by']); ?><br>
                                            <?php endif; ?>
                                        <?php elseif ($event['event_type'] === 'added'): ?>
                                            <strong>📅 Added Date:</strong> <?php echo date('M d, Y \a\t H:i:s', strtotime($event['event_date'])); ?><br>
                                            <strong>🏭 Location:</strong> Warehouse<br>
                                            <?php if ($event['performed_by']): ?>
                                                <strong>👤 Added by:</strong> <?php echo htmlspecialchars($event['performed_by']); ?><br>
                                            <?php endif; ?>
                                        <?php elseif ($event['event_type'] === 'sold'): ?>
                                            <strong>📅 Sold Date:</strong> <?php echo date('M d, Y \a\t H:i:s', strtotime($event['event_date'])); ?><br>
                                            <strong>🏢 Branch:</strong> <?php echo htmlspecialchars($event['branch_name']); ?><br>
                                            <?php if ($event['performed_by']): ?>
                                                <strong>👤 Sold by:</strong> <?php echo htmlspecialchars($event['performed_by']); ?><br>
                                            <?php endif; ?>
                                        <?php endif; ?>

                                        <?php
                                        $details = json_decode($event['details'], true);
                                        if ($details):
                                            foreach ($details as $key => $value):
                                                if ($key === 'sale_amount' || $key === 'effective_price'):
                                                    echo "<strong>" . ucfirst(str_replace('_', ' ', $key)) . ":</strong> MWK " . number_format($value, 2) . "<br>";
                                                elseif ($key === 'customer_name' || $key === 'customer_phone'):
                                                    echo "<strong>" . ucfirst(str_replace('_', ' ', $key)) . ":</strong> " . htmlspecialchars($value) . "<br>";
                                                elseif ($key !== 'source' && $key !== 'verification_date' && $key !== 'verified_by'):
                                                    echo "<strong>" . ucfirst(str_replace('_', ' ', $key)) . ":</strong> " . htmlspecialchars($value) . "<br>";
                                                endif;
                                            endforeach;
                                        endif;
                                        ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

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