<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Sales.php';
require_once __DIR__ . '/../../classes/Deposit.php';
require_once __DIR__ . '/../../classes/Laybuy.php';
require_once __DIR__ . '/../../classes/Branding.php';


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


$auth = new Auth($conn);


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


$userRole = $_SESSION['role'] ?? null;
$userBranchId = null;


if (isset($_SESSION['branch_id'])) {
    $userBranchId = $_SESSION['branch_id'];
} elseif (isset($_SESSION['user_branch_id'])) {
    $userBranchId = $_SESSION['user_branch_id'];
} elseif (isset($_SESSION['branch'])) {
    $userBranchId = $_SESSION['branch'];
} else {

    $sql = "SELECT branch_id FROM users WHERE user_id = :user_id";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && $user['branch_id']) {
        $userBranchId = $user['branch_id'];

        $_SESSION['branch_id'] = $userBranchId;
    }
}


$allowedRoles = ['branch', 'sales', 'warehouse', 'assistant'];
$isAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$canView = $isAdmin || (in_array($userRole, $allowedRoles) && $userBranchId);




if (!$canView) {
    header('Location: ../../unauthorized.php');
    exit;
}


$branch = new Branch($conn);
$sales = new Sales($conn);
$deposit = new Deposit($conn);
$layBuy = new LayBuy($conn);


$reportId = isset($_GET['report_id']) ? intval($_GET['report_id']) : null;

if (!$reportId) {

    header('Location: sales.php');
    exit;
}


$sql = "SELECT wr.*, b.branch_name, u.username as verified_by_name
        FROM weekly_reports wr
        JOIN branches b ON wr.branch_id = b.branch_id
        LEFT JOIN users u ON wr.verified_by = u.user_id
        WHERE wr.report_id = :report_id";

$stmt = $conn->prepare($sql);
$stmt->bindParam(':report_id', $reportId, PDO::PARAM_INT);
$stmt->execute();
$report = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$report) {

    header('Location: sales.php');
    exit;
}
$reportBranding = Branding::documentDetailsForBranchId($conn, (int)$report['branch_id']);


if (!$isAdmin && $report['branch_id'] != $userBranchId) {
    header('Location: ../../unauthorized.php');
    exit;
}

$notification_branch_id=$report['branch_id'];
$weekStartDate = $report['week_start_date'];
$weekEndDate = date('Y-m-d', strtotime($weekStartDate . ' +6 days'));


$salesData = $sales->getDetailedSalesForWeek($report['branch_id'], $weekStartDate, $weekEndDate, $reportId);


$deposits = $deposit->getDepositsForWeek($report['branch_id'], $weekStartDate, $weekEndDate, true, $reportId);
$layBuyPayments = $layBuy->getLayBuyForWeek($reportId);

$totalSales = 0;
if (!empty($salesData)) {
    foreach ($salesData as $sale) {
        $totalSales += $sale['total_price'];
    }
}


$totalDeposits = $deposit->getTotalDeposits($report['branch_id'], $weekStartDate, $weekEndDate, true, $reportId);

$totalLayBuy=0;
if (!empty($layBuyPayments)) {
    foreach ($layBuyPayments as $payment) {
        $totalLayBuy += $payment['body_amount'];
    }
}

$netAmount = ($totalSales+$totalLayBuy) - $totalDeposits;

$updatedTotal=$totalSales+$totalLayBuy;

$updateTotalSales=$sales->updateTotalSales($reportId, $updatedTotal);

/*
if($updateTotalSales){
	echo "Hallo";
}*/
	
if ($isAdmin && isset($_POST['verify_report']) && $report['verification_status'] === 'pending') {
    $verificationResult = $sales->verifyWeeklyReport($report['branch_id'], $weekStartDate, $_SESSION['user_id']);
    if ($verificationResult) {

        header('Location: view_report.php?report_id=' . $reportId . '&verified=1');
        exit;
    }
}











if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['discard_report']) && $isAdmin) {
    $sales->discardReport($reportId, $notification_branch_id);
    header('Location: sales.php');
    exit;
}

?>

    <?php include '../../includes/header.php'; ?>
    <style>
        :root {
            --ink: #172033; --muted: #667085; --line: #e1e6ed; --surface: #fff;
            --canvas: #f2f5f8; --navy: #163a5f; --blue: #2563a6; --soft-blue: #eaf2fb;
            --green: #16845b; --soft-green: #e9f7f1; --amber: #b36a08; --soft-amber: #fff5df;
            --red: #b42318; --radius: 12px; --shadow: 0 12px 35px rgba(23,32,51,.08);
        }
        body { background: var(--canvas); color: var(--ink); }
        .report-page { max-width: 1440px; padding: 28px 24px 56px; }
        .report-header-card { position: relative; overflow: hidden; margin-bottom: 18px; padding: 30px 34px; border: 1px solid #244e76; border-radius: 14px; background: linear-gradient(120deg,#102f4f 0%,#1d4f7d 72%,#27699e 100%); color: #fff; box-shadow: 0 16px 38px rgba(16,47,79,.18); }
        .report-header-card::after { content:''; position:absolute; width:280px; height:280px; right:-90px; top:-150px; border:54px solid rgba(255,255,255,.055); border-radius:50%; }
        .report-header-card .row { position:relative; z-index:1; }
        .report-header-card .eyebrow { margin-bottom:7px; color:#bcd2e5; font-size:.68rem; font-weight:800; letter-spacing:.16em; text-transform:uppercase; }
        .report-header-card h2 { margin:0 0 8px; font-size:1.75rem; font-weight:750; letter-spacing:-.025em; }
        .report-header-card .period { color:#d8e6f1; font-size:.87rem; }
        .report-brand-block { display:flex; align-items:center; gap:18px; }
        .report-brand-logo { width:82px; height:56px; object-fit:contain; padding:6px; border-radius:9px; background:#fff; }
        .status-badge { display:inline-flex; align-items:center; padding:8px 13px; border:1px solid rgba(255,255,255,.24); border-radius:999px; font-size:.72rem; font-weight:800; letter-spacing:.06em; text-transform:uppercase; }
        .verification-info { margin:9px 0 0; color:#d8e6f1; font-size:.76rem; line-height:1.5; }
        .toolbar { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-bottom:20px; padding:12px 14px; border:1px solid var(--line); border-radius:var(--radius); background:var(--surface); box-shadow:0 4px 15px rgba(23,32,51,.04); }
        .toolbar .btn-group-left,.toolbar .btn-group-right { display:flex; flex-wrap:wrap; gap:8px; }
        .toolbar .btn { padding:8px 12px; border-radius:8px; font-size:.78rem; font-weight:700; }
        .summary-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:14px; margin-bottom:20px; }
        .stat-card { position:relative; overflow:hidden; min-height:118px; padding:20px; border:1px solid var(--line); border-radius:var(--radius); background:var(--surface); box-shadow:0 5px 18px rgba(23,32,51,.05); }
        .stat-card::before { content:''; position:absolute; inset:0 auto 0 0; width:4px; background:var(--stat-accent,#2563a6); }
        .stat-card .stat-icon { display:flex; align-items:center; justify-content:center; width:36px; height:36px; margin-bottom:14px; border-radius:9px; background:var(--stat-soft,var(--soft-blue)); color:var(--stat-accent,var(--blue)); font-size:.92rem; }
        .stat-card .stat-label { margin-bottom:4px; color:var(--muted); font-size:.66rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
        .stat-card .stat-value { margin:0; color:var(--ink); font-size:1.2rem; font-weight:800; letter-spacing:-.02em; font-variant-numeric:tabular-nums; }
        .stat-sales { --stat-accent:#2563a6; --stat-soft:#eaf2fb; }.stat-laybuy { --stat-accent:#7657b5; --stat-soft:#f1edfa; }.stat-deposits { --stat-accent:#b36a08; --stat-soft:#fff5df; }.stat-net { --stat-accent:#16845b; --stat-soft:#e9f7f1; }
        .report-section { overflow:hidden; margin-bottom:18px; border:1px solid var(--line); border-radius:var(--radius); background:var(--surface); box-shadow:0 5px 20px rgba(23,32,51,.045); }
        .report-section .section-header { display:flex; align-items:center; justify-content:space-between; min-height:62px; padding:13px 18px; border-bottom:1px solid var(--line); background:#fbfcfd; }
        .report-section .section-header h3 { display:flex; align-items:center; gap:10px; margin:0; color:var(--ink); font-size:.9rem; font-weight:800; }
        .report-section .section-header .section-icon { display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:9px; background:var(--soft-blue); color:var(--blue); font-size:.8rem; }
        .report-section .section-header .badge { padding:6px 9px; border:1px solid var(--line)!important; border-radius:999px; color:var(--muted)!important; background:#fff!important; font-size:.66rem; font-weight:800; }
        .report-section .section-body { padding:0; }
        .report-section table { margin:0; }
        .report-section table th { padding:11px 16px; border:0; border-bottom:1px solid var(--line); background:#fff; color:var(--muted); font-size:.64rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; white-space:nowrap; }
        .report-section table td { padding:12px 16px; border-color:#edf0f4; color:#344054; font-size:.8rem; vertical-align:middle; }
        .report-section tbody tr:hover td { background:#f8fafc; }
        .amount-col { text-align:right; white-space:nowrap; font-weight:700; font-variant-numeric:tabular-nums; }
        .table-total-row td { border-top:2px solid #cdd5df!important; background:#f5f8fb!important; color:var(--ink)!important; font-weight:800!important; }
        .verify-card { display:flex; align-items:center; justify-content:space-between; gap:24px; margin:20px 0 28px; padding:20px 22px; border:1px solid #a9dec8; border-radius:var(--radius); background:var(--soft-green); }
        .verify-card p { margin:0!important; color:#316a54!important; font-size:.82rem; }
        .verify-card .btn { border-radius:8px; white-space:nowrap; font-size:.82rem; font-weight:800; }
        .alert { border:0; border-radius:10px; box-shadow:0 4px 15px rgba(23,32,51,.05); }
        @media(max-width:1050px){.summary-grid{grid-template-columns:1fr 1fr}}
        @media(max-width:720px){.report-page{padding:18px 12px 40px}.report-header-card{padding:24px 20px}.toolbar,.verify-card{align-items:stretch;flex-direction:column}.toolbar .btn-group-left,.toolbar .btn-group-right{width:100%}.toolbar .btn{flex:1}.summary-grid{grid-template-columns:1fr}.stat-card{min-height:0}.report-section table th,.report-section table td{padding:10px 12px}}
        @page { size:A4 landscape; margin:10mm; }
        @media print { body{background:#fff!important;font-size:9pt;print-color-adjust:exact;-webkit-print-color-adjust:exact}.back-btn,.toolbar,header,.btn,.verify-card,footer{display:none!important}.report-page{width:100%;max-width:none;padding:0}.report-header-card{margin-bottom:10px;padding:18px 22px;border:1px solid #7890a6;box-shadow:none}.report-header-card h2{font-size:1.35rem}.summary-grid{grid-template-columns:repeat(4,1fr);gap:7px;margin-bottom:10px}.stat-card{min-height:82px;padding:11px 13px;box-shadow:none}.stat-card .stat-icon{display:none}.stat-card .stat-value{font-size:.95rem}.report-section{margin-bottom:9px;border-radius:0;box-shadow:none;break-inside:auto}.report-section .section-header{min-height:38px;padding:7px 10px}.report-section .section-header .section-icon{width:24px;height:24px}.report-section table th,.report-section table td{padding:5px 8px;font-size:7.5pt}.report-section thead{display:table-header-group}.report-section tr{break-inside:avoid}.modal{display:none!important}}
        @media print {
            body * { visibility: hidden !important; }
            .report-page,
            .report-page * { visibility: visible !important; }
            .report-page {
                position: absolute;
                inset: 0 auto auto 0;
                width: 100% !important;
                margin: 0 !important;
            }
            .report-page .toolbar,
            .report-page .alert,
            .report-page .verify-card,
            .report-page .modal,
            .report-page .btn { display: none !important; }
        }
    </style>
    <main class="container report-page">
        <?php if (isset($_GET['verified']) && $_GET['verified'] == 1): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <strong>Success!</strong> The report has been verified successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="report-header-card">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="report-brand-block">
                        <img class="report-brand-logo" src="<?php echo htmlspecialchars($reportBranding['logo'], ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($reportBranding['name'], ENT_QUOTES, 'UTF-8'); ?> logo">
                        <div>
                            <div class="eyebrow">Weekly Sales Report #<?php echo htmlspecialchars($reportId); ?></div>
                            <h2><?php echo htmlspecialchars($reportBranding['name']); ?> &mdash; <?php echo htmlspecialchars($report['branch_name']); ?></h2>
                            <div class="period">
                                <i class="far fa-calendar-alt me-1"></i>
                                <?php echo date('M d, Y', strtotime($weekStartDate)); ?> &ndash; <?php echo date('M d, Y', strtotime($weekEndDate)); ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                    <span class="badge <?php echo $report['verification_status'] === 'verified' ? 'bg-success' : 'bg-warning text-dark'; ?> status-badge">
                        <i class="fas <?php echo $report['verification_status'] === 'verified' ? 'fa-check-circle' : 'fa-clock'; ?> me-1"></i>
                        <?php echo ucfirst($report['verification_status']); ?>
                    </span>
                    <?php if ($report['verification_status'] === 'verified'): ?>
                        <p class="verification-info">
                            Verified by <?php echo htmlspecialchars($report['verified_by_name']); ?><br>
                            <?php echo date('M d, Y H:i', strtotime($report['verified_at'])); ?>
                        </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="toolbar">
            <div class="btn-group-left">
                <?php if ($isAdmin): ?>
                    <a href="branch_reports.php<?php echo isset($report['branch_id']) ? '?branch_id=' . $report['branch_id'] : ''; ?>" class="btn btn-outline-secondary back-btn">
                        <i class="fas fa-arrow-left"></i> Back to Reports
                    </a>
                <?php else: ?>
                    <a href="branch_reports.php" class="btn btn-outline-secondary back-btn">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                <?php endif; ?>
                <button type="button" id="printReportBtn" class="btn btn-outline-primary">
                    <i class="fas fa-print"></i> Print Report
                </button>
            </div>
            <?php if ($isAdmin): ?>
                <div class="btn-group-right">
                    <form method="POST" action="#" class="d-inline">
                        <button type="submit" name="request_edit" id="request_edit" class="btn btn-warning">
                            <i class="fas fa-pen"></i> Request Branch Edit
                        </button>
                    </form>
                    <a href="edit_week_r.php?report_id=<?php echo $reportId; ?>" class="btn btn-success">
                        <i class="fas fa-calendar-alt"></i> Edit Week Dates
                    </a>
                    <button type="button" id="discard_report" class="btn btn-danger">
                        <i class="fas fa-trash-alt"></i> Discard Report
                    </button>
                </div>
            <?php endif; ?>
        </div>

        <section class="summary-grid" aria-label="Report financial summary">
            <div class="stat-card stat-sales"><div class="stat-icon"><i class="fas fa-cash-register"></i></div><div class="stat-label">Sales Revenue</div><p class="stat-value">MWK <?php echo number_format($totalSales, 2); ?></p></div>
            <div class="stat-card stat-laybuy"><div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div><div class="stat-label">Laybuy Payments</div><p class="stat-value">MWK <?php echo number_format($totalLayBuy, 2); ?></p></div>
            <div class="stat-card stat-deposits"><div class="stat-icon"><i class="fas fa-university"></i></div><div class="stat-label">Deposits Deducted</div><p class="stat-value">MWK <?php echo number_format($totalDeposits, 2); ?></p></div>
            <div class="stat-card stat-net"><div class="stat-icon"><i class="fas fa-chart-line"></i></div><div class="stat-label">Net Report Amount</div><p class="stat-value">MWK <?php echo number_format($netAmount, 2); ?></p></div>
        </section>

        <div class="report-section">
            <div class="section-header">
                <h3><span class="section-icon"><i class="fas fa-receipt"></i></span> Sales Records</h3>
                <span class="badge bg-light text-dark border"><?php echo $salesData ? count($salesData) : 0; ?> item<?php echo ($salesData && count($salesData) === 1) ? '' : 's'; ?></span>
            </div>
            <div class="section-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Item Name</th>
                                <th>Code</th>
                                <th class="amount-col">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($salesData): ?>
                                <?php foreach ($salesData as $sale): ?>
                                    <tr>
                                        <td><?php echo date('d M y', strtotime($sale['sold_at'])); ?></td>
                                        <td><?php echo htmlspecialchars(trim((string)$sale['item_name'] . (!empty($sale['item_details']) ? ' - ' . $sale['item_details'] : ''))); ?></td>
                                        <td><span class="text-muted"><?php echo htmlspecialchars($sale['unique_code']); ?></span></td>
                                        <td class="amount-col">MWK <?php echo number_format($sale['total_price'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr class="table-total-row">
                                    <td colspan="3" class="text-end">Total Sales</td>
                                    <td class="amount-col">MWK <?php echo number_format($totalSales, 2); ?></td>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">No sales data available for this report.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="report-section">
            <div class="section-header">
                <h3><span class="section-icon"><i class="fas fa-hand-holding-usd"></i></span> Laybuy Payments</h3>
                <span class="badge bg-light text-dark border"><?php echo $layBuyPayments ? count($layBuyPayments) : 0; ?> payment<?php echo ($layBuyPayments && count($layBuyPayments) === 1) ? '' : 's'; ?></span>
            </div>
            <div class="section-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Item Name</th>
                                <th class="amount-col">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($layBuyPayments): ?>
                                <?php foreach ($layBuyPayments as $payment): ?>
                                    <tr>
                                        <td><?php echo date('d M y', strtotime($payment['payment_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($payment['notes']); ?></td>
                                        <td class="amount-col">MWK <?php echo number_format($payment['body_amount'], 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr class="table-total-row">
                                    <td colspan="2" class="text-end">Total Laybuy Payments</td>
                                    <td class="amount-col">MWK <?php echo number_format($totalLayBuy, 2); ?></td>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted py-4">No laybuy payments recorded for this report.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="report-section">
            <div class="section-header">
                <h3><span class="section-icon"><i class="fas fa-university"></i></span> Deposits</h3>
                <span class="badge bg-light text-dark border"><?php echo $deposits ? count($deposits) : 0; ?> deposit<?php echo ($deposits && count($deposits) === 1) ? '' : 's'; ?></span>
            </div>
            <div class="section-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th class="amount-col">Amount</th>
                                <th>Notes</th>
                                <th>Recorded By</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($deposits): ?>
                                <?php foreach ($deposits as $deposit): ?>
                                    <tr>
                                        <td><?php echo date('Y-m-d', strtotime($deposit['deposit_date'])); ?></td>
                                        <td class="amount-col">MWK <?php echo number_format($deposit['amount'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($deposit['notes'] ?? ''); ?></td>
                                        <td><?php echo htmlspecialchars($deposit['created_by_user'] ?? 'System'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr class="table-total-row">
                                    <td class="text-end">Total Deposits</td>
                                    <td class="amount-col">MWK <?php echo number_format($totalDeposits, 2); ?></td>
                                    <td colspan="2"></td>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">No deposits recorded for this report.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <?php if ($isAdmin && $report['verification_status'] === 'pending'): ?>
            <div class="verify-card">
                <p class="mb-3 text-muted">Once verified, this report's sales and deposits will be locked in and reflected on the admin dashboard.</p>
                <form method="post" onsubmit="return confirm('Are you sure you want to verify this report? This action cannot be undone.')">
                    <button type="submit" name="verify_report" class="btn btn-lg btn-success">
                        <i class="fas fa-check-circle"></i> Verify This Report
                    </button>
                </form>
            </div>
        <?php endif; ?>

        <div class="modal" tabindex="-1" id="exampleModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-exclamation-triangle text-danger me-2"></i>Discard Report</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p>Are you sure you want to discard this report? All associated sales and deposits will be reversed and the branch will be notified. This process cannot be undone.</p>
                    </div>
                    <div class="modal-footer">
                        <form method="POST">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" name="discard_report" value="1" class="btn btn-danger">Yes, Discard Report</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </main>

    <script>

        document.getElementById('printReportBtn').addEventListener('click', function() {
            window.print();
        });

        var discardReportBtn = document.getElementById('discard_report');
        if (discardReportBtn) {
            discardReportBtn.addEventListener('click', function() {
                bootstrap.Modal.getOrCreateInstance(document.getElementById('exampleModal')).show();
            });
        }
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
