<?php
require_once __DIR__ . '/../../includes/header.php';
require_once __DIR__ . '/../../classes/Deposit.php';

$depositModel = new Deposit($conn);
$depositId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($depositId <= 0) {
    header('Location: ' . $auth->getDashboardUrl());
    exit();
}

$depositData = $depositModel->getDepositById($depositId);

if (!$depositData) {
    http_response_code(404);
    echo '<div class="container mt-4"><div class="alert alert-danger">Deposit not found.</div></div>';
    include __DIR__ . '/../../includes/footer.php';
    exit();
}

$isAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = (int)$auth->getUserBranch($_SESSION['user_id']);
$depositBranchId = (int)$depositData['branch_id'];
$depositBranding = Branding::documentDetailsForBranchId($conn, $depositBranchId);

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

$settings = Branding::settings();
$currencyCode = $settings['currency_code'] ?? 'MWK';
$notes = trim((string)($depositData['notes'] ?? ''));
$isVerified = $notes !== '' && strpos($notes, '[Verified in Report #') !== false;
$reportId = (int)($depositData['report_id'] ?? 0);

if ($reportId <= 0 && preg_match('/\[Verified in Report #(\d+)\]/', $notes, $matches)) {
    $reportId = (int)$matches[1];
}

function depositPreviewDate($date, $format = 'F j, Y') {
    if (empty($date)) {
        return 'N/A';
    }

    try {
        return (new DateTime($date))->format($format);
    } catch (Exception $e) {
        return 'N/A';
    }
}
?>

<style>
    .deposit-preview-header {
        display: flex;
        justify-content: space-between;
        gap: 20px;
        align-items: flex-start;
        margin-bottom: 20px;
    }

    .deposit-document {
        background: #fff;
        border: 1px solid #d6dbe1;
        margin-bottom: 24px;
    }

    .deposit-document-header {
        display: flex;
        justify-content: space-between;
        gap: 24px;
        padding: 24px;
        border-bottom: 2px solid #343a40;
    }

    .deposit-brand {
        display: flex;
        gap: 18px;
        align-items: center;
    }

    .deposit-brand img {
        max-height: 90px;
        max-width: 210px;
        object-fit: contain;
    }

    .deposit-brand h1 {
        font-size: 22px;
        margin: 0;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

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

    .deposit-title h2 {
        font-size: 20px;
        margin: 0;
    }

    .deposit-title p {
        margin: 4px 0 0;
        color: #6c757d;
    }

    .deposit-document-body {
        padding: 24px;
    }

    .deposit-amount {
        border: 1px solid #e1e5ea;
        padding: 18px;
        margin-bottom: 20px;
        background: #f8f9fa;
    }

    .deposit-amount strong {
        display: block;
        color: #495057;
        font-size: 12px;
        text-transform: uppercase;
    }

    .deposit-amount span {
        font-size: 30px;
        font-weight: 700;
        color: #198754;
    }

    .deposit-detail-grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 16px;
        margin-bottom: 20px;
    }

    .deposit-detail {
        border: 1px solid #e1e5ea;
        padding: 14px;
        min-height: 86px;
    }

    .deposit-detail strong {
        display: block;
        color: #495057;
        font-size: 12px;
        margin-bottom: 6px;
        text-transform: uppercase;
    }

    .deposit-notes {
        border: 1px solid #e1e5ea;
        padding: 14px;
        min-height: 90px;
    }

    @media (max-width: 768px) {
        .deposit-preview-header,
        .deposit-document-header {
            display: block;
        }

        .deposit-title {
            margin-top: 18px;
            text-align: left;
        }

        .deposit-detail-grid {
            grid-template-columns: 1fr;
        }
    }

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

        body {
            background: #fff;
        }

        .container {
            max-width: none;
            width: 100%;
        }

        .deposit-document {
            border: 0;
        }
    }
</style>

<div class="container mt-4">
    <div class="deposit-preview-header no-print">
        <div>
            <h2 class="mb-1">Bank Deposit #<?php echo htmlspecialchars($depositData['id']); ?></h2>
            <p class="text-muted mb-0">Read-only deposit preview</p>
        </div>
        <div>
            <a href="<?php echo htmlspecialchars($auth->getDashboardUrl()); ?>" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
            <button type="button" onclick="window.print()" class="btn btn-outline-secondary">
                <i class="fas fa-print"></i> Print
            </button>
        </div>
    </div>

    <section class="deposit-document">
        <div class="deposit-document-header">
            <div class="deposit-brand">
                <img src="<?php echo htmlspecialchars($depositBranding['logo']); ?>" alt="<?php echo htmlspecialchars($depositBranding['name']); ?> Logo">
                <div>
                    <h1><?php echo htmlspecialchars($depositBranding['name']); ?></h1>
                    <?php $companyDetails = $depositBranding; ?>
                    <?php if (!empty($companyDetails['tagline'])): ?>
                        <p class="mb-0"><?php echo htmlspecialchars($companyDetails['tagline']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
            <div class="deposit-title">
                <h2>Bank Deposit Preview</h2>
                <p>Deposit #<?php echo htmlspecialchars($depositData['id']); ?></p>
                <p>Printed: <?php echo htmlspecialchars(date('F j, Y H:i')); ?></p>
            </div>
        </div>

        <div class="deposit-document-body">
            <div class="deposit-amount">
                <strong>Deposit Amount</strong>
                <span><?php echo htmlspecialchars($currencyCode); ?> <?php echo number_format((float)$depositData['amount'], 2); ?></span>
            </div>

            <div class="deposit-detail-grid">
                <div class="deposit-detail">
                    <strong>Branch</strong>
                    <?php echo htmlspecialchars($depositData['branch_name'] ?? ('Branch #' . $depositData['branch_id'])); ?>
                </div>
                <div class="deposit-detail">
                    <strong>Status</strong>
                    <span class="badge <?php echo $isVerified ? 'bg-success' : 'bg-warning text-dark'; ?>">
                        <?php echo $isVerified ? 'Verified' : 'Unverified'; ?>
                    </span>
                </div>
                <div class="deposit-detail">
                    <strong>Deposit Date</strong>
                    <?php echo htmlspecialchars(depositPreviewDate($depositData['deposit_date'])); ?>
                </div>
                <div class="deposit-detail">
                    <strong>Recorded At</strong>
                    <?php echo htmlspecialchars(depositPreviewDate($depositData['created_at'] ?? null, 'F j, Y H:i')); ?>
                </div>
                <div class="deposit-detail">
                    <strong>Recorded By</strong>
                    <?php echo htmlspecialchars($depositData['created_by_user'] ?? 'System'); ?>
                </div>
                <div class="deposit-detail">
                    <strong>Weekly Report</strong>
                    <?php if ($reportId > 0): ?>
                        <a href="../reports/view_report.php?report_id=<?php echo $reportId; ?>">Report #<?php echo $reportId; ?></a>
                    <?php else: ?>
                        Not submitted
                    <?php endif; ?>
                </div>
            </div>

            <div class="deposit-notes">
                <strong>Notes</strong>
                <div class="mt-2">
                    <?php echo $notes !== '' ? nl2br(htmlspecialchars($notes)) : 'No notes recorded.'; ?>
                </div>
            </div>
        </div>
    </section>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
