<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/StockTaking.php';

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

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

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

$sessionId = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
if (!$sessionId) {
    header('Location: stocktaking_dashboard.php');
    exit();
}

$itemStatus = strtolower(trim($_GET['item_status'] ?? 'all'));
if (!in_array($itemStatus, ['found', 'missing', 'extra', 'all'], true)) {
    $itemStatus = 'all';
}

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    $userBranch = $auth->getUserBranch($_SESSION['user_id']);
    $sessionSql = "SELECT branch_id FROM stock_taking_sessions WHERE session_id = :session_id";
    $sessionStmt = $conn->prepare($sessionSql);
    $sessionStmt->bindValue(':session_id', $sessionId, PDO::PARAM_INT);
    $sessionStmt->execute();
    $sessionAccess = $sessionStmt->fetch(PDO::FETCH_ASSOC);

    if (!$sessionAccess || $sessionAccess['branch_id'] != $userBranch) {
        header('Location: stocktaking_dashboard.php');
        exit();
    }
}

$stockTaking = new StockTaking($conn);
$report = $stockTaking->getSessionReport($sessionId);
if (isset($report['error'])) {
    die('Error: ' . htmlspecialchars($report['error']));
}

$session = $report['session'];
$sessionBranding = Branding::documentDetailsForBranchId($conn, (int)($session['branch_id'] ?? 0));
$companyName = $sessionBranding['name'];
$companyLogo = $sessionBranding['logo'];
$companyLogoFile = $sessionBranding['logo_file'];
$summary = $report['summary'];
$itemSummary = $stockTaking->getItemQuantitySummary($sessionId);

$allItems = array_merge($report['found_items'], $report['missing_items'], $report['extra_items']);
$displayItems = $itemStatus === 'all' ? $allItems : ($report[$itemStatus . '_items'] ?? []);

$verifierNames = [];
$verifiedByIds = array_values(array_unique(array_filter(array_map(function ($item) {
    return isset($item['verified_by']) ? (int)$item['verified_by'] : null;
}, $displayItems))));

if (!empty($verifiedByIds)) {
    $placeholders = implode(',', array_fill(0, count($verifiedByIds), '?'));
    $userStmt = $conn->prepare("SELECT user_id, username FROM users WHERE user_id IN ($placeholders)");
    foreach ($verifiedByIds as $index => $userId) {
        $userStmt->bindValue($index + 1, $userId, PDO::PARAM_INT);
    }
    $userStmt->execute();
    foreach ($userStmt->fetchAll(PDO::FETCH_ASSOC) as $user) {
        $verifierNames[(int)$user['user_id']] = $user['username'];
    }
}

function reportDate($value, $format = 'F j, Y g:i A') {
    if (empty($value)) {
        return 'N/A';
    }

    return date($format, strtotime($value));
}

function statusLabel($status) {
    return ucwords(str_replace('_', ' ', (string)$status));
}

$generatedBy = $auth->getUserName($_SESSION['user_id']) ?: ($_SESSION['username'] ?? 'Unknown');
$statusTitle = $itemStatus === 'all' ? 'All Items' : statusLabel($itemStatus) . ' Items';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Taking Report - Session #<?php echo (int)$sessionId; ?></title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <style>
        body {
            background: #f4f6f8;
            color: #212529;
            font-size: 13px;
        }

        .report-page {
            max-width: 1180px;
            margin: 24px auto;
            background: #fff;
            padding: 28px;
            border: 1px solid #d9dee3;
        }

        .report-top {
            display: flex;
            justify-content: space-between;
            gap: 24px;
            border-bottom: 2px solid #212529;
            padding-bottom: 16px;
            margin-bottom: 18px;
        }

        .logo {
            max-height: 76px;
            width: auto;
            margin-bottom: 8px;
        }

        .company-name {
            font-size: 22px;
            font-weight: 700;
            margin: 0;
        }

        .report-title {
            text-align: right;
        }

        .report-title h1 {
            font-size: 26px;
            margin: 0 0 8px;
            font-weight: 700;
        }

        .meta-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-bottom: 18px;
        }

        .meta-box,
        .summary-box {
            border: 1px solid #d9dee3;
            padding: 10px;
            min-height: 64px;
        }

        .label {
            display: block;
            color: #6c757d;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: .03em;
            margin-bottom: 3px;
        }

        .value {
            font-weight: 700;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-bottom: 20px;
        }

        .summary-number {
            display: block;
            font-size: 24px;
            line-height: 1;
            font-weight: 700;
        }

        .section-title {
            font-size: 17px;
            margin: 22px 0 10px;
            padding-bottom: 6px;
            border-bottom: 1px solid #d9dee3;
            font-weight: 700;
        }

        .table {
            margin-bottom: 0;
        }

        .table th {
            background: #eef1f4;
            white-space: nowrap;
        }

        .badge-status {
            display: inline-block;
            min-width: 64px;
            padding: 4px 8px;
            border-radius: 4px;
            color: #fff;
            text-align: center;
            font-size: 12px;
            font-weight: 700;
        }

        .badge-found { background: #198754; }
        .badge-missing { background: #dc3545; }
        .badge-extra { background: #0dcaf0; color: #000; }

        .notes-box {
            border: 1px solid #d9dee3;
            padding: 12px;
            min-height: 52px;
            white-space: pre-wrap;
        }

        .signature-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 28px;
            margin-top: 42px;
        }

        .signature-line {
            border-top: 1px solid #212529;
            padding-top: 6px;
            text-align: center;
            color: #495057;
        }

        .print-actions {
            max-width: 1180px;
            margin: 16px auto 0;
            text-align: right;
        }

        @media print {
            body {
                background: #fff;
                font-size: 11px;
            }

            .print-actions,
            .navbar,
            nav {
                display: none !important;
            }

            .report-page {
                max-width: none;
                margin: 0;
                padding: 0;
                border: 0;
            }

            .meta-box,
            .summary-box,
            tr {
                break-inside: avoid;
                page-break-inside: avoid;
            }

            .section-title {
                break-after: avoid;
                page-break-after: avoid;
            }
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>
    <div class="print-actions">
        <button class="btn btn-primary" onclick="window.print()">Print</button>
        <button class="btn btn-secondary" onclick="window.close()">Close</button>
    </div>

    <main class="report-page">
        <header class="report-top">
            <div>
                <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" class="logo">
                <p class="company-name"><?php echo htmlspecialchars($companyName); ?></p>
                <div>P.O. Box 109, Limbe, Malawi, South East Africa</div>
                <div>Tel: +265 (0) 212 273 707 / Cell: +265 (0) 888 737 654</div>
            </div>
            <div class="report-title">
                <h1>Stock Taking Report</h1>
                <div><strong>Session #:</strong> <?php echo (int)$sessionId; ?></div>
                <div><strong>Printed Items:</strong> <?php echo htmlspecialchars($statusTitle); ?></div>
                <div><strong>Generated:</strong> <?php echo date('F j, Y g:i A'); ?></div>
                <div><strong>Generated By:</strong> <?php echo htmlspecialchars($generatedBy); ?></div>
            </div>
        </header>

        <section class="meta-grid">
            <div class="meta-box">
                <span class="label">Branch</span>
                <span class="value"><?php echo htmlspecialchars($session['branch_name'] ?? 'N/A'); ?></span>
            </div>
            <div class="meta-box">
                <span class="label">Session Date</span>
                <span class="value"><?php echo reportDate($session['session_date'] ?? null, 'F j, Y'); ?></span>
            </div>
            <div class="meta-box">
                <span class="label">Status</span>
                <span class="value"><?php echo htmlspecialchars(statusLabel($session['session_status'] ?? 'completed')); ?></span>
            </div>
            <div class="meta-box">
                <span class="label">Completed</span>
                <span class="value"><?php echo reportDate($session['completed_at'] ?? null); ?></span>
            </div>
            <div class="meta-box">
                <span class="label">Auditor</span>
                <span class="value"><?php echo htmlspecialchars($session['auditor_name'] ?? 'N/A'); ?></span>
            </div>
            <div class="meta-box">
                <span class="label">Admin Started</span>
                <span class="value"><?php echo htmlspecialchars($session['admin_started_name'] ?? 'N/A'); ?></span>
                <div><?php echo reportDate($session['admin_started_at'] ?? null); ?></div>
            </div>
            <div class="meta-box">
                <span class="label">Branch Started</span>
                <span class="value"><?php echo htmlspecialchars($session['branch_started_name'] ?? 'N/A'); ?></span>
                <div><?php echo reportDate($session['branch_started_at'] ?? null); ?></div>
            </div>
            <div class="meta-box">
                <span class="label">Final Verification</span>
                <span class="value">
                    Admin: <?php echo htmlspecialchars($session['admin_verified_name'] ?? 'N/A'); ?><br>
                    Branch: <?php echo htmlspecialchars($session['branch_verified_name'] ?? 'N/A'); ?>
                </span>
            </div>
        </section>

        <section class="summary-grid">
            <div class="summary-box">
                <span class="label">System Total</span>
                <span class="summary-number"><?php echo (int)($summary['total_system'] ?? 0); ?></span>
            </div>
            <div class="summary-box">
                <span class="label">Items Found</span>
                <span class="summary-number"><?php echo (int)($summary['total_found'] ?? 0); ?></span>
            </div>
            <div class="summary-box">
                <span class="label">Items Missing</span>
                <span class="summary-number"><?php echo (int)($summary['total_missing'] ?? 0); ?></span>
            </div>
            <div class="summary-box">
                <span class="label">Extra Items</span>
                <span class="summary-number"><?php echo (int)($summary['total_extra'] ?? 0); ?></span>
            </div>
        </section>

        <?php if (!isset($itemSummary['error']) && !empty($itemSummary)): ?>
            <h2 class="section-title">Item Quantity Summary</h2>
            <div class="table-responsive">
                <table class="table table-bordered table-sm">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th class="text-center">System Total</th>
                            <th class="text-center">Found</th>
                            <th class="text-center">Missing</th>
                            <th class="text-center">Extra</th>
                            <th class="text-center">Verified</th>
                            <th class="text-center">Pending</th>
                            <th class="text-center">Completion</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($itemSummary as $item): ?>
                            <?php
                            $systemQty = (int)($item['total_system_quantity'] ?? 0);
                            $verifiedQty = (int)($item['verified_quantity'] ?? 0);
                            $completion = $systemQty > 0 ? round(($verifiedQty / $systemQty) * 100, 1) : 0;
                            ?>
                            <tr>
                                <td><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small></td>
                                <td class="text-center"><?php echo $systemQty; ?></td>
                                <td class="text-center"><?php echo (int)($item['found_quantity'] ?? 0); ?></td>
                                <td class="text-center"><?php echo (int)($item['missing_quantity'] ?? 0); ?></td>
                                <td class="text-center"><?php echo (int)($item['extra_quantity'] ?? 0); ?></td>
                                <td class="text-center"><?php echo $verifiedQty; ?></td>
                                <td class="text-center"><?php echo (int)($item['pending_quantity'] ?? 0); ?></td>
                                <td class="text-center"><?php echo $completion; ?>%</td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <h2 class="section-title"><?php echo htmlspecialchars($statusTitle); ?> Details (<?php echo count($displayItems); ?>)</h2>
        <div class="table-responsive">
            <table class="table table-bordered table-sm">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Status</th>
                        <th>Unique Code</th>
                        <th>Item Name</th>
                        <th>Location / Last Known</th>
                        <th>Verified By</th>
                        <th>Verified At</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($displayItems)): ?>
                        <?php foreach ($displayItems as $index => $item): ?>
                            <?php
                            $status = $item['status'] ?? '';
                            $verifiedById = isset($item['verified_by']) ? (int)$item['verified_by'] : 0;
                            $verifiedBy = $verifierNames[$verifiedById] ?? ($verifiedById ? 'User #' . $verifiedById : 'N/A');
                            ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><span class="badge-status badge-<?php echo htmlspecialchars($status); ?>"><?php echo htmlspecialchars(statusLabel($status)); ?></span></td>
                                <td><?php echo htmlspecialchars($item['unique_code'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small></td>
                                <td><?php echo htmlspecialchars($item['location_found'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($verifiedBy); ?></td>
                                <td><?php echo reportDate($item['verified_at'] ?? null); ?></td>
                                <td><?php echo htmlspecialchars($item['notes'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="text-center">No records found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <h2 class="section-title">Session Notes</h2>
        <div class="notes-box"><?php echo htmlspecialchars($session['notes'] ?? 'No notes recorded.'); ?></div>

        <section class="signature-grid">
            <div class="signature-line">Admin / Warehouse Signature</div>
            <div class="signature-line">Branch Manager Signature</div>
            <div class="signature-line">Date</div>
        </section>
    </main>

    <script>
        window.addEventListener('load', function () {
            if (window.location.search.indexOf('autoprint=1') !== -1) {
                window.print();
            }
        });
    </script>
</body>
</html>
