<?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';


$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);


$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;
}


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


$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);


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


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


$netAmount = $totalSales - $totalDeposits;


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;
    }
}
?>

    <style>
        .report-section {
            margin-bottom: 30px;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            background-color: #fff;
        }
        .summary-section {
            background-color: #f8f9fa;
        }
        .status-badge {
            font-size: 0.9rem;
            padding: 0.35rem 0.65rem;
        }
        .action-btns {
            margin-bottom: 20px;
        }
        .verification-info {
            font-style: italic;
            color: #6c757d;
        }
        .summary-card {
            transition: transform 0.3s;
        }
        .summary-card:hover {
            transform: translateY(-5px);
        }


        @media print {
            .back-btn, .action-btns, header, .btn {
                display: none !important;
            }
            .container {
                width: 100%;
                max-width: 100%;
            }
            body {
                font-size: 12pt;
            }
            .report-section {
                break-inside: avoid;
                box-shadow: none;
                border: 1px solid #ddd;
            }
        }
    </style>
    <?php include '../../includes/header.php'; ?>

    <div class="container mt-4">
        <?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="row action-btns">
            <div class="col-sm-6 mb-2">
                <?php if ($isAdmin): ?>
                    <a href="branch_reports.php<?php echo isset($report['branch_id']) ? '?branch_id=' . $report['branch_id'] : ''; ?>" class="btn btn-secondary back-btn">
                        <i class="fas fa-arrow-left"></i> Back to Reports
                    </a>
                <?php else: ?>
                    <a href="branch_reports.php" class="btn btn-secondary back-btn">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                <?php endif; ?>
            </div>
            <div class="col-sm-6 text-sm-end mb-2">
                <button type="button" id="printReportBtn" class="btn btn-primary">
                    <i class="fas fa-print"></i> Print Report
                </button>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-8">
                <h2><?php echo htmlspecialchars($report['branch_name']); ?> - Weekly Report</h2>
                <p>
                    <strong>Report Date:</strong> <?php echo date('M d, Y', strtotime($weekStartDate)); ?>
                </p>
            </div>
            <div class="col-md-4 text-md-end">
                <span class="badge <?php echo $report['verification_status'] === 'verified' ? 'bg-success' : 'bg-warning'; ?> status-badge">
                    <?php echo ucfirst($report['verification_status']); ?>
                </span>
                <?php if ($report['verification_status'] === 'verified'): ?>
                    <p class="verification-info mt-2">
                        Verified by <?php echo htmlspecialchars($report['verified_by_name']); ?> on
                        <?php echo date('M d, Y H:i', strtotime($report['verified_at'])); ?>
                    </p>
                <?php endif; ?>
            </div>
        </div>


        <div class="report-section">
            <h3>1. Sales Records</h3>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Item Name</th>
                            <th>Code</th>
                            <th>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><?php echo htmlspecialchars($sale['unique_code']); ?></td>
                                    <td>MWK <?php echo number_format($sale['total_price'], 2); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <tr class="table-info fw-bold">
                                <td colspan="3" class="text-end">Total Sales:</td>
                                <td>MWK <?php echo number_format($totalSales, 2); ?></td>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center">No sales data available for this report.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>


        <div class="report-section">
            <h3>2. Deposits</h3>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>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>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-info fw-bold">
                                <td colspan="1" class="text-end">Total Deposits:</td>
                                <td>MWK <?php echo number_format($totalDeposits, 2); ?></td>
                                <td colspan="2"></td>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center">No deposits recorded for this report.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>


        <div class="report-section summary-section">
            <h3>3. Financial Summary</h3>
            <div class="row mt-4">
                <div class="col-md-4 mb-3">
                    <div class="card summary-card bg-primary text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">Total Sales</h5>
                            <p class="card-text">MWK <?php echo number_format($totalSales, 2); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="card summary-card bg-success text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">Total Deposits</h5>
                            <p class="card-text">MWK <?php echo number_format($totalDeposits, 2); ?></td>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="card summary-card bg-info text-white">
                        <div class="card-body text-center">
                            <h5 class="card-title">Net Amount</h5>
                            <p class="card-text">MWK <?php echo number_format($netAmount, 2); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($isAdmin && $report['verification_status'] === 'pending'): ?>
            <div class="row mt-4 mb-5">
                <div class="col-12 text-center">
                    <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>
            </div>
        <?php endif; ?>
    </div>

    <script>

        document.getElementById('printReportBtn').addEventListener('click', function() {
            window.print();
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
