<?php

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


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

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$sales = new Sales($conn);
$deposit = new Deposit($conn);
$branch = new Branch($conn);
$laybuy =new LayBuy($conn);

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    die("Access denied. Only administrators can access this page.");
}


$branchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;
if (!$branchId) {
    die("Error: Branch ID is required.");
}


$branchInfo = $branch->getBranchById($branchId);
if (!$branchInfo) {
    die("Error: Branch not found.");
}

$LayBuyPayment = new Laybuy($conn);
$paymentData = $LayBuyPayment->getWeeklyPaymentDetails($recordId, $branchId) ?? [];



$today = new DateTime();
$currentWeekStart = new DateTime('Monday this week');
$currentWeekEnd = new DateTime('Sunday this week');


$currentWeekData = $sales->generateWeeklyReport(
    $branchId,
    $currentWeekStart->format('Y-m-d'),
    $currentWeekEnd->format('Y-m-d')
);


$reportData = $currentWeekData;
$totalAmount = 0;


$deposits = $deposit->getDepositsForWeek(
    $branchId,
    $currentWeekStart->format('Y-m-d'),
    $currentWeekEnd->format('Y-m-d')
);


$totalDeposits = $deposit->getTotalDeposits(
    $branchId,
    $currentWeekStart->format('Y-m-d'),
    $currentWeekEnd->format('Y-m-d')
);


$totalSales = 0;
foreach ($currentWeekData as $sale) {
    $totalSales += (float)$sale['amount'];
}


$totalLaybuy = 0;
foreach ($paymentData as $payment) {
    $totalLaybuy += (float)($payment['body_amount'] ?? 0);
}




//$totalLaybuy=61000;

$totalSales+=$totalLaybuy;



$netAmount = $totalSales - $totalDeposits;


$lastUpdateTime = date('Y-m-d H:i:s');
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f8f9fa;
        }

        .admin-header {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            border-radius: 8px;
        }

        .report-section {
            margin-bottom: 2rem;
            padding: 1.5rem;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .real-time-data {
            background-color: #f8f9fa;
            border-left: 4px solid #28a745;
        }

        .summary-section {
            background-color: #e9ecef;
            border-left: 4px solid #007bff;
        }

        .deposit-section {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
        }

        .admin-badge {
            background-color: #dc3545;
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .real-time-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            background-color: #28a745;
            border-radius: 50%;
            margin-right: 0.5rem;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .last-updated {
            background-color: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 4px;
            padding: 0.75rem;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }

        .readonly-notice {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 4px;
            padding: 1rem;
            margin-bottom: 2rem;
        }

        .branch-info-card {
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 2rem;
        }

        .print-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            border-radius: 50px;
            padding: 15px 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        @media print {
            .no-print {
                display: none !important;
            }

            .print-btn {
                display: none !important;
            }

            .admin-header {
                background: #dc3545 !important;
                -webkit-print-color-adjust: exact;
            }
        }
    </style>
    <div class="container mt-4">

        <div class="row mb-4 no-print">
            <div class="col-12">
                <a href="branch_selection.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Branch Selection
                </a>
                <a href="../dashbord/admin.php" class="btn btn-outline-secondary ms-2">
                    <i class="fas fa-tachometer-alt"></i> Admin Dashboard
                </a>
            </div>
        </div>


        <div class="admin-header text-center">
            <h1>
                <i class="fas fa-chart-line"></i>
                Sales Monitoring - <?php echo htmlspecialchars($branchInfo['branch_name']); ?>
            </h1>
            <p class="mb-0">
                <span class="admin-badge">ADMIN VIEW</span>
                <span class="ms-3">
                    <span class="real-time-indicator"></span>
                    Real-time Data Access
                </span>
            </p>
        </div>













        <div class="branch-info-card">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="fas fa-store text-primary"></i> Branch Information</h5>
                    <p><strong>Name:</strong> <?php echo htmlspecialchars($branchInfo['branch_name']); ?></p>
                    <p><strong>Location:</strong> <?php echo htmlspecialchars($branchInfo['location'] ?? 'Not specified'); ?></p>
                </div>
                <div class="col-md-6">
                    <h5><i class="fas fa-clock text-primary"></i> Monitoring Details</h5>
                    <p><strong>Viewing Period:</strong> <?php echo $currentWeekStart->format('Y-m-d') . ' to ' . $currentWeekEnd->format('Y-m-d'); ?></p>
                    <p><strong>Data Type:</strong> Real-time (Live)</p>
                </div>
            </div>
        </div>


        <div class="last-updated">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <i class="fas fa-sync-alt text-primary"></i>
                    <strong>Last Updated:</strong> <?php echo $lastUpdateTime; ?>
                </div>
                <div>
                    <small class="text-muted">Data refreshes automatically every 5 minutes</small>
                </div>
            </div>
        </div>


        <div class="report-section real-time-data">
            <h2><i class="fas fa-chart-bar"></i> Current Week's Sales (Real-time)</h2>
            <h4>Week: <?php echo $currentWeekStart->format('Y-m-d') . ' to ' . $currentWeekEnd->format('Y-m-d'); ?></h4>

            <?php

            include 'admin_report_table.php';
            ?>
        </div>
		
		
		
		  <div class="report-section real-time-data">
            <h2>2. All Unverified Laybuy Payments  (Real-time)</h2>
            <h4>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h4>

            <?php
            error_log("Report data before table: " . print_r($currentWeekData, true));
            include 'admin_laybuy_report_table.php';
            ?>
        </div>


        <div class="report-section deposit-section">
            <h2><i class="fas fa-university"></i> Deposits for the Week</h2>
            <h4>Week: <?php echo $currentWeekStart->format('Y-m-d') . ' to ' . $currentWeekEnd->format('Y-m-d'); ?></h4>


            <div class="mt-4">
                <table class="table table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th><i class="fas fa-calendar-alt"></i> Date</th>
                            <th><i class="fas fa-dollar-sign"></i> Amount</th>
                            <th><i class="fas fa-sticky-note"></i> Notes</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($deposits && count($deposits) > 0) {
                            foreach ($deposits as $depositRecord) {
                                echo "<tr>";
                                echo "<td>" . htmlspecialchars($depositRecord['deposit_date']) . "</td>";
                                echo "<td>MWK" . number_format($depositRecord['amount'], 2) . "</td>";
                                echo "<td>" . htmlspecialchars($depositRecord['notes'] ?? 'N/A') . "</td>";
                                echo "</tr>";
                            }
                        } else {
                            echo "<tr><td colspan='3' class='text-center text-muted'>";
                            echo "<i class='fas fa-inbox'></i> No deposits recorded for this week";
                            echo "</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>


        <div class="report-section summary-section">
            <h2><i class="fas fa-calculator"></i> Financial Summary</h2>
            <div class="row">
                <div class="col-md-4">
                    <div class="card border-success">
                        <div class="card-body text-center">
                            <i class="fas fa-chart-line text-success" style="font-size: 2rem;"></i>
                            <h5 class="card-title mt-2">Total Sales</h5>
                            <h3 class="card-text text-success">MWK<?php echo number_format($totalSales, 2); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-warning">
                        <div class="card-body text-center">
                            <i class="fas fa-university text-warning" style="font-size: 2rem;"></i>
                            <h5 class="card-title mt-2">Total Deposits</h5>
                            <h3 class="card-text text-warning">MWK<?php echo number_format($totalDeposits, 2); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-primary">
                        <div class="card-body text-center">
                            <i class="fas fa-balance-scale text-primary" style="font-size: 2rem;"></i>
                            <h5 class="card-title mt-2">Net Amount</h5>
                            <h3 class="card-text <?php echo $netAmount >= 0 ? 'text-success' : 'text-danger'; ?>">
                                MWK<?php echo number_format($netAmount, 2); ?>
                            </h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="report-section">
            <h2><i class="fas fa-tachometer-alt"></i> Performance Indicators</h2>
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">
                                <i class="fas fa-shopping-cart"></i> Total Transactions
                            </h5>
                            <h3 class="text-info"><?php echo count($currentWeekData); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">
                                <i class="fas fa-chart-bar"></i> Average Transaction Value
                            </h5>
                            <h3 class="text-info">
                                MWK<?php echo count($currentWeekData) > 0 ? number_format($totalSales / count($currentWeekData), 2) : '0.00'; ?>
                            </h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>






    <script>

        setInterval(function() {
            location.reload();
        }, 300000);


        window.addEventListener('beforeunload', function() {
            document.body.style.opacity = '0.7';
            document.body.style.pointerEvents = 'none';
        });


        document.title = document.title + ' - Updated: ' + new Date().toLocaleTimeString();


        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>