<?php
// TEMPORARY: show errors on screen to diagnose the blank-page issue. Remove once diagnosed.
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

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__ . '/../../includes/dashboard_helper.php';
require_once __DIR__ . '/../../classes/Laybuy.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../classes/CreditSales.php';


if (!function_exists('getDashboardLink')) {
    function getDashboardLink() {
        if (isset($_SESSION['role'])) {
            switch ($_SESSION['role']) {
                case 'super_admin':
                    return '../dashboard/admin.php';
                case 'branch_manager':
                case 'warehouse_personnel':
                    return '../dashboard/branch.php';
                default:
                    return '../dashboard/branch.php';
            }
        }
        return '../dashboard/branch.php';
    }
}


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

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$systemSettings = new SystemSettings();
$eisEnabled = $systemSettings->eisEnabled();
$sales = new Sales($conn);
$deposit = new Deposit($conn);
$laybuy =new LayBuy($conn);
$orderObj = new Order($conn);
$creditSalesObj = new CreditSales($conn);



if (!$auth->isBranchManager($_SESSION['user_id']) && !$auth->isWarehousePersonnel($_SESSION['user_id'])) {
    die("Access denied. Only branch managers and warehouse personnel can access this page.");
}

$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    die("Error: You are not assigned to any branch.");
}

$LayBuyPayment = new Laybuy($conn);
$paymentData = $LayBuyPayment->getWeeklyPaymentDetails(null, $branchId) ?? [];
$orderPaymentData = $orderObj->getUnverifiedPayments($branchId) ?? [];
$creditPaymentData = $creditSalesObj->getUnverifiedPayments($branchId) ?? [];






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


$isMonday = $today->format('N') === '1';
$previousWeekStart = (clone $currentWeekStart)->modify('-1 week');
$previousWeekEnd = (clone $currentWeekEnd)->modify('-1 week');



$salesExist = $sales->checkSalesExist($branchId);
error_log("Sales exist check: " . ($salesExist ? "Yes" : "No"));


try {
    $currentWeekData = $sales->generateWeeklyReport(
        $branchId,
        $currentWeekStart->format('Y-m-d'),
        $currentWeekEnd->format('Y-m-d')
    );
    $reportData = (is_array($currentWeekData) ? $currentWeekData : []);
} catch (Exception $e) {
    error_log("Error generating weekly report: " . $e->getMessage());
    $reportData = [];
}


$totalAmount = 0;


error_log("Current week start: " . $currentWeekStart->format('Y-m-d'));
error_log("Current week end: " . $currentWeekEnd->format('Y-m-d'));
error_log("Current week data: " . print_r($reportData, true));


echo "";


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


error_log("Deposits for the week: " . print_r($deposits, true));


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


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



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

$weekStartStr = $currentWeekStart->format('Y-m-d');
$weekEndStr = $currentWeekEnd->format('Y-m-d');

$totalOrderPayments = 0;
foreach ($orderPaymentData as $orderPayment) {
    $paymentDay = date('Y-m-d', strtotime($orderPayment['payment_date'] ?? 'now'));
    // Older unverified order payments belong to a prior report and are shown for
    // reference only in the table — they must not inflate this week's net amount.
    if ($paymentDay >= $weekStartStr && $paymentDay <= $weekEndStr) {
        $totalOrderPayments += (float)($orderPayment['amount'] ?? 0);
    }
}

$totalCreditPayments = 0;
foreach ($creditPaymentData as $creditPayment) {
    $totalCreditPayments += (float)($creditPayment['amount'] ?? 0);
}

$totalSales += $totalLaybuy;
$totalSales += $totalOrderPayments;
$totalSales += $totalCreditPayments;


$netAmount = $totalSales - $totalDeposits;










if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_report'])) {
    $weekToVerify = $_POST['week_start_date'];
    
	if($netAmount!=0){
		   $errorMessage = "Error! you cannot submit this report. Sales and deposits do not match";
     
	}else{
		if(($totalSales==0)||($totalDeposits==0)){
			$errorMessage = "Error! you cannot submit this report. Empty Sales and Deposits detected";
     	}else{			
				
				$verified = $sales->verifyWeeklyReport(
					$branchId,
					$weekToVerify,
					$_SESSION['user_id']
				);
				
				
				
				if ($verified) {
					$successMessage = "All unverified sales and deposits have been successfully verified and sent to the admin. They will now appear in the admin's sales dashboard and will be removed from this view.";
				} else {
					$errorMessage = "Error verifying report. Please try again.";
				}
				
		}
	}
	 
}

?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        .report-section {
            margin-bottom: 2rem;
            padding: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
        }
        .needs-verification {
            background-color: #fff3cd;
        }
        .real-time-data {
            background-color: #f8f9fa;
        }
        .summary-section {
            background-color: #e9ecef;
        }
        .action-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 2rem;
        }
    </style>
    <div class="container mt-5">
        <div class="row mb-4">
            <div class="col-12">
                <a href="<?php echo getDashboardLink(); ?>" class="btn btn-secondary">Back to Dashboard</a>
            </div>
        </div>


                <?php if (isset($successMessage) || (isset($_GET['success']) && !empty($_GET['success']))): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($successMessage ?? $_GET['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (isset($errorMessage) || (isset($_GET['error']) && !empty($_GET['error']))): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($errorMessage ?? $_GET['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>


        <div class="report-section real-time-data">
            <h2>1. All Unverified Sales (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 '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 'laybuy_report_table.php';
            ?>
        </div>

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

            <?php include 'order_payments_report_table.php'; ?>
        </div>

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

            <?php include 'credit_payments_report_table.php'; ?>
        </div>


        <div class="report-section">
            <h2>5. All Unverified Deposits</h2>
            <h4>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h4>


            <div class="mb-4">
                <h3>Add New Deposit </h3>
                <form action="processdp.php" method="POST" class="needs-validation" novalidate>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="deposit_date">Deposit Date</label>
                            <input type="date" class="form-control" id="deposit_date" name="deposit_date" required>
                            <div class="invalid-feedback">Please select a date.</div>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="deposit_amount">Amount (MWK)</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">MWK</span>
                                </div>
                                <input type="number" step="0.01" min="0.01" class="form-control" id="deposit_amount" name="deposit_amount" required>
                                <div class="invalid-feedback">Please enter a valid amount.</div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="deposit_notes">Notes (Optional)</label>
                        <textarea class="form-control" id="deposit_notes" name="deposit_notes" rows="2"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Record Deposit
                    </button>
                </form>
            </div>


            <div class="mt-4">
                <h3>Unverified Deposit Records</h3>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Amount</th>
                            <th>Notes</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if (!empty($deposits) && is_array($deposits)) {
                            foreach ($deposits as $deposit) {
                                $isUnverified = empty($deposit['notes']) || strpos($deposit['notes'], '[Verified in Report #') === false;
                                echo "<tr>";
                                echo "<td>" . htmlspecialchars(date('Y-m-d', strtotime($deposit['deposit_date'] ?? 'now'))) . "</td>";
                                echo "<td>MWK " . number_format($deposit['amount'] ?? 0, 2) . "</td>";
                                echo "<td>" . htmlspecialchars($deposit['notes'] ?? 'N/A') . "</td>";
                                echo "<td>";
                                if ($isUnverified && isset($deposit['deposit_id'])) {
                                    echo "<a href='edit_deposit.php?id=" . htmlspecialchars($deposit['deposit_id']) . "' class='btn btn-sm btn-primary me-1'><i class='fas fa-edit'></i> Edit</a>";
                                    echo "<form action='process_deposit_action.php' method='POST' style='display:inline;' onsubmit='return confirmDelete(\"deposit\");'>";
                                    echo "<input type='hidden' name='deposit_id' value='" . htmlspecialchars($deposit['deposit_id']) . "'>";
                                    echo "<button type='submit' name='delete_deposit' class='btn btn-sm btn-danger'><i class='fas fa-trash'></i> Delete</button>";
                                    echo "</form>";
                                } else {
                                    echo "<span class='text-muted'>N/A</span>";
                                }
                                echo "</td>";
                                echo "</tr>";
                            }
                        } else {
                            echo "<tr><td colspan='4' class='text-center'>No unverified deposits found</td></tr>";
                        }
                        ?>
                    </tbody>
                    <?php if (!empty($deposits)): ?>
                    <tfoot>
                        <tr>
                            <td class="text-end"><strong>Total Deposits</strong></td>
                            <td><strong>MWK <?php echo number_format($totalDeposits, 2); ?></strong></td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                    <?php endif; ?>
                </table>
            </div>
        </div>


        <div class="report-section summary-section">
            <h2>6. Financial Summary</h2>
            <div class="row">
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Total Sales</h5>
                            <p class="card-text mb-1">MWK <?php echo number_format($totalSales, 2); ?></p>
                            <small class="text-muted">Incl. laybuy MWK <?php echo number_format($totalLaybuy, 2); ?>, orders MWK <?php echo number_format($totalOrderPayments, 2); ?>, credit sales MWK <?php echo number_format($totalCreditPayments, 2); ?></small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Total Deposits</h5>
                            <p class="card-text">MWK <?php echo number_format($totalDeposits, 2); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Net Amount</h5>
                            <p class="card-text">MWK <?php echo number_format($netAmount, 2); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="action-buttons">
            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#previewModal">
                <i class="fas fa-eye"></i> Preview Unverified Data
            </button>
        </div>


        <div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="previewModalLabel">Unverified Sales and Deposits Report</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" id="printableArea">

                        <div class="preview-section mb-4">
                            <h3>All Unverified Sales</h3>
                            <h5>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h5>
                            <p class="text-info"><i class="fas fa-info-circle"></i> This report includes all unverified sales. After verification, these sales will be marked as verified and sent to the admin.</p>
                            <?php
                            $reportData = $currentWeekData;
                            $totalAmount = 0;
                            include 'report_table.php';
                            ?>
                        </div>

                        <div class="preview-section mb-4">
                            <h3>All Unverified Laybuy Payments</h3>
                            <h5>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h5>
                            <p class="text-info"><i class="fas fa-info-circle"></i> This report includes all unverified laybuy payments. After verification, these will be marked as verified and sent to the admin.</p>
                            <?php include 'laybuy_report_table.php'; ?>
                        </div>

                        <div class="preview-section mb-4">
                            <h3>All Unverified Order Payments</h3>
                            <h5>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h5>
                            <p class="text-info"><i class="fas fa-info-circle"></i> This report includes all unverified order payments. After verification, these will be marked as verified and sent to the admin.</p>
                            <?php include 'order_payments_report_table.php'; ?>
                        </div>

                        <div class="preview-section mb-4">
                            <h3>All Unverified Credit Sale Payments</h3>
                            <h5>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h5>
                            <p class="text-info"><i class="fas fa-info-circle"></i> This report includes all unverified credit sale payments. After verification, these will be marked as verified and sent to the admin.</p>
                            <?php include 'credit_payments_report_table.php'; ?>
                        </div>


                        <div class="preview-section mb-4">
                            <h3>All Unverified Deposits</h3>
                            <h5>Current Week: <?php echo $currentWeekStart->format('D-m-y') . ' to ' . $currentWeekEnd->format('D-m-y'); ?></h5>
                            <p class="text-info"><i class="fas fa-info-circle"></i> This report includes all unverified deposits. After verification, they will be marked as verified and sent to the admin.</p>
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Notes</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    if (!empty($deposits) && is_array($deposits)) {
                                        foreach ($deposits as $deposit) {
                                            echo "<tr>";
                                            echo "<td>" . htmlspecialchars(date('Y-m-d', strtotime($deposit['deposit_date'] ?? 'now'))) . "</td>";
                                            echo "<td>MWK " . number_format($deposit['amount'] ?? 0, 2) . "</td>";
                                            echo "<td>" . htmlspecialchars($deposit['notes'] ?? 'N/A') . "</td>";
                                            echo "</tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='3' class='text-center'>No unverified deposits found</td></tr>";
                                    }
                                    ?>
                                </tbody>
                                <?php if (!empty($deposits)): ?>
                                <tfoot>
                                    <tr>
                                        <td class="text-end"><strong>Total Deposits</strong></td>
                                        <td><strong>MWK <?php echo number_format($totalDeposits, 2); ?></strong></td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                                <?php endif; ?>
                            </table>
                        </div>


                        <div class="preview-section mb-4">
                            <h3>Financial Summary</h3>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-body">
                                            <h5 class="card-title">Total Sales</h5>
                                            <p class="card-text mb-1">MWK <?php echo number_format($totalSales, 2); ?></p>
                                            <small class="text-muted">Incl. laybuy MWK <?php echo number_format($totalLaybuy, 2); ?>, orders MWK <?php echo number_format($totalOrderPayments, 2); ?>, credit sales MWK <?php echo number_format($totalCreditPayments, 2); ?></small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-body">
                                            <h5 class="card-title">Total Deposits</h5>
                                            <p class="card-text">MWK <?php echo number_format($totalDeposits, 2); ?></p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-body">
                                            <h5 class="card-title">Net Amount</h5>
                                            <p class="card-text">MWK <?php echo number_format($netAmount, 2); ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <form method="POST">
                            <input type="hidden" name="week_start_date" value="<?php echo $currentWeekStart->format('Y-m-d'); ?>">
                            <button type="submit" name="verify_report" class="btn btn-success">
                                <i class="fas fa-check-circle"></i> Send Report to Admin
                            </button>
                        </form>
                        <button type="button" class="btn btn-primary" onclick="printPreview()">
                            <i class="fas fa-print"></i> Print Preview
                        </button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>


    </div>

    <script>

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


        function printPreview() {
            const printContent = document.getElementById('printableArea').innerHTML;
            const originalContent = document.body.innerHTML;

            document.body.innerHTML = `
                <div class="container mt-4">
                    <h2 class="text-center mb-4">Unverified Sales and Deposits Report</h2>
                    ${printContent}
                </div>
            `;

            window.print();
            document.body.innerHTML = originalContent;

            bootstrap.Modal.getOrCreateInstance(document.getElementById('previewModal')).show();
        }


        (function() {
            'use strict';
            window.addEventListener('load', function() {
                document.getElementById('deposit_date').valueAsDate = new Date();

                var forms = document.getElementsByClassName('needs-validation');
                Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();


        function confirmDelete(type) {
            return confirm(`Are you sure you want to delete this ${type}? ${type === 'sale' ? 'This will delete all items in the same transaction.' : ''}`);
        }
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>