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


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


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

if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit;
}


$branches = [];
$items = null;
$branchId = null;
$branchName = null;
$searchTerm = '';
$searchField = 's.unique_code';


$stmtBranches = $conn->prepare("SELECT branch_id, branch_name FROM branches ORDER BY branch_name");
$stmtBranches->execute();
$branches = $stmtBranches->fetchAll(PDO::FETCH_ASSOC);


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['branch_id'])) {
    $branchId = filter_input(INPUT_POST, 'branch_id', FILTER_SANITIZE_NUMBER_INT);

    if ($branchId !== null && $branchId !== '') {

        $stmtBranchName = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
        $stmtBranchName->execute([$branchId]);
        $branchName = $stmtBranchName->fetchColumn();

        $stmtCount = $conn->prepare("SELECT COUNT(*) FROM sold_items WHERE branch_id = ?");
        $stmtCount->execute([$branchId]);
        $itemCount = (int)$stmtCount->fetchColumn();
        $items = []; // rows are now fetched by the DataTable via AJAX; this only gates which section renders
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        .container { max-width: 1400px; margin: 0 auto; padding: 20px; }
        .header {
            display: flex; justify-content: space-between; align-items: center;
            margin-bottom: 30px; background: rgba(255, 255, 255, 0.95);
            padding: 20px 30px; border-radius: 15px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        .back-btn {
            display: inline-flex; align-items: center; gap: 8px; padding: 12px 20px;
            background: #6c757d; color: white; text-decoration: none; border-radius: 8px;
            font-weight: 500; transition: all 0.3s ease;
        }
        .back-btn:hover { background: #5a6268; transform: translateY(-2px); color: white; text-decoration: none; }
        .page-title {
            text-align: center; margin-bottom: 40px; color: white;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        .page-title h1 { font-size: 2.5rem; font-weight: 700; }
        .page-title p { font-size: 1.1rem; opacity: 0.9; }
        .workflow-container, .search-container, .report-container {
            background: rgba(255, 255, 255, 0.95); border-radius: 20px;
            padding: 30px; margin-bottom: 30px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
        }
        .workflow-steps { display: flex; justify-content: space-around; margin-bottom: 30px; position: relative; }
        .workflow-steps::before {
            content: ''; position: absolute; top: 25px; left: 25%; right: 25%;
            height: 2px; background: #e9ecef; z-index: 1;
        }
        .step { display: flex; flex-direction: column; align-items: center; position: relative; z-index: 2; }
        .step-number {
            width: 50px; height: 50px; border-radius: 50%; background: #e9ecef; color: #6c757d;
            display: flex; align-items: center; justify-content: center;
            font-weight: 700; font-size: 18px; margin-bottom: 10px; transition: all 0.3s ease;
        }
        .step.active .step-number { background: linear-gradient(45deg, #667eea, #764ba2); color: white; }
        .step.completed .step-number { background: #28a745; color: white; }
        .step-title { font-weight: 600; color: #2c3e50; text-align: center; font-size: 14px; }
        .section-title {
            font-size: 1.3rem; font-weight: 600; color: #2c3e50; margin-bottom: 20px;
            display: flex; align-items: center; gap: 10px;
        }
        .section-icon {
            width: 35px; height: 35px; background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 8px; display: flex; align-items: center; justify-content: center;
            color: white; font-size: 16px;
        }
        .form-control {
            width: 100%; padding: 14px 16px; border: 2px solid #e9ecef; border-radius: 10px;
            font-size: 16px; transition: all 0.3s ease; background: white;
        }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        .search-grid { display: grid; grid-template-columns: 1fr 2fr auto auto; gap: 20px; align-items: end; }
        .form-group { display: flex; flex-direction: column; }
        .form-label { font-weight: 600; color: #2c3e50; margin-bottom: 8px; }
        .btn {
            padding: 12px 20px; border: none; border-radius: 8px; font-size: 14px;
            font-weight: 600; cursor: pointer; transition: all 0.3s ease; text-decoration: none;
            display: inline-flex; align-items: center; gap: 8px; white-space: nowrap;
        }
        .btn-primary { background: linear-gradient(45deg, #667eea, #764ba2); color: white; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3); }
        .btn-secondary { background: #6c757d; color: white; }
        .btn-secondary:hover { background: #5a6268; }
        .btn-success { background: linear-gradient(45deg, #28a745, #20c997); color: white; }
        .report-container { padding: 0; overflow: hidden; }
        .report-header {
            background: linear-gradient(45deg, #667eea, #764ba2); color: white;
            padding: 20px 30px; display: flex; justify-content: space-between; align-items: center;
        }
        .report-title { font-size: 1.4rem; font-weight: 600; display: flex; align-items: center; gap: 10px; }
        .report-stats { display: flex; gap: 20px; font-size: 14px; align-items: center; }
        .stat-item { display: flex; align-items: center; gap: 5px; }
        .table-container { overflow-x: auto; max-height: 600px; }
        .report-table { width: 100%; border-collapse: collapse; font-size: 14px; }
        .report-table th {
            background: #f8f9fa; padding: 15px 12px; text-align: left; font-weight: 600;
            color: #2c3e50; border-bottom: 2px solid #e9ecef; position: sticky; top: 0; z-index: 10;
        }
        .report-table td { padding: 12px; border-bottom: 1px solid #e9ecef; vertical-align: middle; }
        .report-table tbody tr:hover { background: #f8f9fa; }
        .alert-info {
            padding: 16px 20px; border-radius: 12px; margin: 25px; display: flex;
            align-items: center; gap: 12px; font-weight: 500;
            background: linear-gradient(45deg, #17a2b8, #138496); color: white; border: none;
        }
        .price-cell { font-weight: 600; color: #28a745; }
        .id-cell { font-family: 'Courier New', monospace; font-size: 12px; color: #6c757d; }
        .loading-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.5); display: none; justify-content: center;
            align-items: center; z-index: 9999;
        }
        .loading-content {
            background: white; padding: 30px; border-radius: 15px; text-align: center;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }
        .loading-spinner {
            width: 40px; height: 40px; border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea; border-radius: 50%;
            animation: spin 1s linear infinite; margin: 0 auto 15px;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        @media print {
            body { background: white !important; }
            .no-print { display: none !important; }
            .report-container { box-shadow: none; border: 1px solid #ddd; }
            .report-header { background: #f8f9fa !important; color: #333 !important; }
        }
        @media (max-width: 768px) {
            .search-grid { grid-template-columns: 1fr; gap: 15px; }
            .header { flex-direction: column; gap: 15px; }
        }
    </style>

    <div class="container">
        <div class="no-print">

            <div class="header">
                <a href="<?php echo getDashboardLink(); ?>" class="back-btn">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
                <div style="display: flex; align-items: center; gap: 15px;">
                    <i class="fas fa-user-circle" style="font-size: 24px; color: #667eea;"></i>
                    <span style="font-weight: 600; color: #2c3e50;">
                        <?php echo htmlspecialchars($_SESSION['username']); ?> (<?php echo ucfirst(htmlspecialchars($_SESSION['role'])); ?>)
                    </span>
                </div>
            </div>


            <div class="page-title">
                <h1>Sold Items Dashboard</h1>
                <p>Review sold items from any branch</p>
            </div>


            <div class="workflow-container">
                <div class="workflow-steps">
                    <div class="step <?php echo ($branchId !== null) ? 'completed' : 'active'; ?>">
                        <div class="step-number">1</div>
                        <div class="step-title">Select Branch</div>
                    </div>
                    <div class="step <?php echo ($items !== null) ? 'active' : ''; ?>">
                        <div class="step-number">2</div>
                        <div class="step-title">View Report</div>
                    </div>
                </div>

                <form id="branchForm" method="POST">
                    <div class="section-title">
                        <div class="section-icon"><i class="fas fa-building"></i></div>
                        Step 1: Select Branch Location
                    </div>
                    <select name="branch_id" id="branch_id" class="form-control" required onchange="this.form.submit()">
                        <option value="">Choose a branch to view its sales report...</option>
                        <?php foreach ($branches as $branch): ?>
                            <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>"
                                <?php echo ($branchId == $branch['branch_id']) ? 'selected' : ''; ?>>
                                🏪 <?php echo htmlspecialchars($branch['branch_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div>
        </div>


        <?php if ($branchId !== null && $items !== null): ?>
            <div class="report-container">
                <div class="report-header">
                    <div class="report-title">
                        <i class="fas fa-file-invoice-dollar"></i>
                        Sales Report for <?php echo htmlspecialchars($branchName); ?>
                    </div>
                    <div class="report-stats">
                        <div class="stat-item"><i class="fas fa-check-circle"></i><span><?php echo $itemCount; ?> Sales</span></div>
                        <div class="stat-item"><i class="fas fa-calendar"></i><span><?php echo date('M d, Y'); ?></span></div>
                        <div class="no-print">
                            <button type="button" id="printBtn" class="btn btn-success"><i class="fas fa-print"></i> Print</button>
                            <a href="generate_sold_items_pdf.php?branch_id=<?php echo htmlspecialchars($branchId); ?>&search_field=<?php echo htmlspecialchars($searchField); ?>&search_term=<?php echo urlencode($searchTerm); ?>" class="btn btn-primary" title="Download PDF">
                                <i class="fas fa-file-pdf"></i> PDF
                            </a>
                        </div>
                    </div>
                </div>

                <div class="table-container">
                    <table class="report-table" id="example">
                        <thead>
                            <tr>
                                <th>Unique Code</th>
                                <th>Item Name</th>
                                <th>Item Details</th>
                                <th>Price</th>
                                <th>Condition</th>
                                <th>Warranty</th>
                                <th>Serial Number</th>
                                <th>Date Sold</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        <?php elseif ($branchId === null): ?>
            <div class="alert alert-info no-print">
                <i class="fas fa-arrow-up"></i>
                Please select a branch above to view its sales report.
            </div>
        <?php endif; ?>
    </div>


    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="loading-spinner"></div>
            <h3>Loading Report...</h3>
            <p>Please wait while we retrieve the data.</p>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const branchSelect = document.getElementById('branch_id');
            const branchForm = document.getElementById('branchForm');
            const printBtn = document.getElementById('printBtn');
            const loadingOverlay = document.getElementById('loadingOverlay');

            function showLoading() {
                if (loadingOverlay) loadingOverlay.style.display = 'flex';
            }

            if (branchSelect) {
                branchSelect.addEventListener('change', function() {
                    if (this.value !== '') {
                        showLoading();
                        branchForm.submit();
                    }
                });
            }

            if (printBtn) {
                printBtn.addEventListener('click', function() {
                    window.print();
                });
            }


            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'p' && printBtn) {
                    e.preventDefault();
                    printBtn.click();
                }
            });

            const exampleTable = document.getElementById('example');
            if (exampleTable) {
                new DataTable('#example', {
                    serverSide: true,
                    processing: true,
                    ordering: false,
                    pageLength: 25,
                    order: [[7, 'desc']],
                    ajax: {
                        url: '../../ajax/inventory/sold_items_dashboard_data.php',
                        type: 'GET',
                        data: function (d) {
                            d.branch_id = <?php echo json_encode($branchId); ?>;
                        }
                    },
                    columns: [
                        { data: 'unique_code' },
                        { data: 'item_name' },
                        { data: 'item_details' },
                        { data: 'unit_price' },
                        { data: 'condition_status' },
                        { data: 'warranty' },
                        { data: 'serial_number' },
                        { data: 'sold_at' },
                        { data: 'verified' }
                    ]
                });
            }
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
