<?php
session_start();
require_once '../config/database.php';

// Admin or Teacher access
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

// AJAX: save receipt display settings
if (isset($_POST['ajax']) && $_POST['ajax'] === 'save_display_settings') {
    header('Content-Type: application/json');
    try {
        $allowed = ['receipt_font', 'receipt_font_size', 'receipt_wm_text', 'receipt_wm_color', 'receipt_wm_opacity', 'receipt_wm_size'];
        foreach ($allowed as $key) {
            if (isset($_POST[$key])) {
                $val = trim($_POST[$key]);
                $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, created_at)
                    VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()");
                $stmt->execute([$key, $val, $val]);
            }
        }
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit();
}

$receipt_data = null;
$error_message = '';
$search_id = $_GET['id'] ?? '';

// Load bank receipt settings from DB
$receipt_settings = [
    'school_name'   => '',
    'address'       => '',
    'receipt_title' => 'মানি রিসিপ্ট',
    'subtitle'      => '',
    'watermark'     => 'PAID',
];

// Load display/customize settings
$display_settings = [
    'receipt_font'       => "'Hind Siliguri', sans-serif",
    'receipt_font_size'  => '14',
    'receipt_wm_text'    => 'PAID',
    'receipt_wm_color'   => '#008000',
    'receipt_wm_opacity' => '7',
    'receipt_wm_size'    => '8',
];

try {
    $s = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'bank_receipt_%' OR setting_key LIKE 'receipt_%'");
    while ($row = $s->fetch()) {
        $key = str_replace('bank_receipt_', '', $row['setting_key']);
        if (isset($receipt_settings[$key]) && !empty($row['setting_value'])) {
            $receipt_settings[$key] = $row['setting_value'];
        }
        if (isset($display_settings[$row['setting_key']]) && !empty($row['setting_value'])) {
            $display_settings[$row['setting_key']] = $row['setting_value'];
        }
    }
    // wm_text fallback to watermark setting
    if ($display_settings['receipt_wm_text'] === 'PAID' && !empty($receipt_settings['watermark'])) {
        $display_settings['receipt_wm_text'] = $receipt_settings['watermark'];
    }
} catch (Exception $e) { /* use defaults */ }

if ($search_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT
                fp.id as payment_id, fp.transaction_id, fp.payment_date, fp.payment_method, fp.amount, fp.notes,
                f.fee_type, f.month, f.academic_year,
                s.first_name, s.last_name, s.roll_number, s.session,
                c.name as class_name, c.section
            FROM fee_payments fp
            JOIN fees f ON fp.fee_id = f.id
            JOIN students s ON f.student_id = s.id
            JOIN classes c ON s.class_id = c.id
            WHERE fp.id = :sid1 OR fp.transaction_id = :sid2
            LIMIT 1
        ");
        $stmt->execute(['sid1' => $search_id, 'sid2' => $search_id]);
        $receipt_data = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$receipt_data) {
            $error_message = "এই আইডি বা ট্রানজেকশন আইডির জন্য কোনো রসিদ পাওয়া যায়নি।";
        }
    } catch (Exception $e) {
        $error_message = "রসিদ খোঁজার সময় একটি ত্রুটি হয়েছে: " . $e->getMessage();
    }
}

function numberToWordsBengali($num) {
    $num = (float)$num;
    $taka = (int)floor($num);
    $paisa = (int)round(($num - $taka) * 100);

    $ones = ['', 'এক', 'দুই', 'তিন', 'চার', 'পাঁচ', 'ছয়', 'সাত', 'আট', 'নয়',
             'দশ', 'এগারো', 'বারো', 'তেরো', 'চৌদ্দ', 'পনেরো', 'ষোলো', 'সতেরো', 'আঠারো', 'উনিশ'];
    $tens = ['', '', 'বিশ', 'ত্রিশ', 'চল্লিশ', 'পঞ্চাশ', 'ষাট', 'সত্তর', 'আশি', 'নব্বই'];

    function inWords($n, $ones, $tens) {
        if ($n === 0) return '';
        if ($n < 20) return $ones[$n];
        if ($n < 100) return $tens[(int)($n/10)] . ($n % 10 ? ' ' . $ones[$n % 10] : '');
        if ($n < 1000) return $ones[(int)($n/100)] . ' শত' . ($n % 100 ? ' ' . inWords($n % 100, $ones, $tens) : '');
        if ($n < 100000) return inWords((int)($n/1000), $ones, $tens) . ' হাজার' . ($n % 1000 ? ' ' . inWords($n % 1000, $ones, $tens) : '');
        if ($n < 10000000) return inWords((int)($n/100000), $ones, $tens) . ' লক্ষ' . ($n % 100000 ? ' ' . inWords($n % 100000, $ones, $tens) : '');
        return inWords((int)($n/10000000), $ones, $tens) . ' কোটি' . ($n % 10000000 ? ' ' . inWords($n % 10000000, $ones, $tens) : '');
    }

    $result = 'কথায়: ';
    if ($taka > 0) $result .= inWords($taka, $ones, $tens) . ' টাকা';
    if ($paisa > 0) $result .= ($taka > 0 ? ' ' : '') . inWords($paisa, $ones, $tens) . ' পয়সা';
    if ($taka === 0 && $paisa === 0) $result .= 'শূন্য টাকা';
    $result .= ' মাত্র';
    return $result;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি রসিদ</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Hind Siliguri', sans-serif; background-color: #f4f7f6; }
        .memo-box { font-family: <?php echo htmlspecialchars($display_settings['receipt_font']); ?>; font-size: <?php echo (int)$display_settings['receipt_font_size']; ?>px; }
        .memo-container { max-width: 820px; margin: 2rem auto; }
        .memo-box { background: white; border: 2px solid #000; padding: 20px 25px; position: relative; overflow: hidden; border-radius: 10px; }

        /* Watermark */
        .paid-watermark { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-45deg); font-size: 8rem; color: rgba(0,128,0,0.07); font-weight: bold; z-index: 1; pointer-events: none; text-transform: uppercase; }

        /* 3-column header */
        .memo-header-3col {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            border-bottom: 2px solid #000;
            padding-bottom: 14px;
            margin-bottom: 18px;
            position: relative;
            z-index: 2;
            gap: 10px;
        }
        .header-left { flex: 0 0 25%; font-size: 0.85rem; line-height: 1.6; }
        .header-right { flex: 0 0 35%; font-size: 0.85rem; line-height: 1.6; }
        .header-center { flex: 0 0 36%; text-align: center; }
        .header-right { text-align: right; }
        .header-label { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; color: #666; margin-bottom: 4px; font-weight: 600; }
        .header-center h3 { font-size: 1.1rem; font-weight: 700; margin-bottom: 4px; }
        .header-center p { font-size: 0.8rem; margin-bottom: 3px; color: #444; }
        .receipt-subtitle { font-weight: 600; color: #333; }
        .memo-title-badge { display: inline-block; border: 2px solid #000; padding: 3px 14px; font-weight: bold; font-size: 0.95rem; margin-top: 6px; }
        .txn-id { font-size: 0.82rem; }

        /* Table & footer */
        .memo-table th, .memo-table td { padding: 10px 14px; }
        .memo-footer { margin-top: 25px; display: flex; justify-content: space-between; align-items: flex-end; position: relative; z-index: 2; }
        .amount-in-words { font-style: italic; font-weight: 500; }
        .signature-area { text-align: center; }
        .signature-area .line { border-top: 1px solid #000; margin-top: 45px; width: 180px; }

        @media print {
            body { background-color: white; }
            .no-print { display: none !important; }
            .memo-container { margin: 0; max-width: 100%; }
            .memo-box { box-shadow: none; border-radius: 0; border: 2px solid #000; }
            .paid-watermark { -webkit-print-color-adjust: exact; color-adjust: exact; }
        }
    </style>
</head>
<body>

<div class="container no-print mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header">
                    <h5><i class="fas fa-search"></i> রসিদ অনুসন্ধান করুন</h5>
                </div>
                <div class="card-body">
                    <form method="GET" action="">
                        <div class="input-group">
                            <input type="text" name="id" class="form-control"
                                   placeholder="পেমেন্ট আইডি বা ট্রানজেকশন আইডি দিন..."
                                   value="<?php echo htmlspecialchars($search_id); ?>" required>
                            <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i> খুঁজুন</button>
                        </div>
                    </form>
                    <?php if ($error_message): ?>
                        <div class="alert alert-danger mt-3"><?php echo $error_message; ?></div>
                    <?php endif; ?>
                </div>
                <div class="card-footer text-center">
                    <a href="manage.php"><i class="fas fa-arrow-left"></i> ফি ব্যবস্থাপনায় ফিরে যান</a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if ($receipt_data): ?>
<div class="memo-container">
    <div class="memo-box">
        <div class="paid-watermark" id="receiptWatermark" style="color:<?php
            $hex = $display_settings['receipt_wm_color'];
            $op  = (int)$display_settings['receipt_wm_opacity'] / 100;
            $r = hexdec(substr($hex,1,2)); $g = hexdec(substr($hex,3,2)); $b = hexdec(substr($hex,5,2));
            echo "rgba($r,$g,$b,$op)";
        ?>; font-size:<?php echo (int)$display_settings['receipt_wm_size']; ?>rem;"><?php echo htmlspecialchars($display_settings['receipt_wm_text']); ?></div>

        <!-- 3-column header -->
        <div class="memo-header-3col">

            <!-- Left: Recipient info -->
            <div class="header-left">
                <div class="header-label">প্রাপক</div>
                <strong><?php echo htmlspecialchars($receipt_data['first_name'] . ' ' . $receipt_data['last_name']); ?></strong><br>
                <?php echo 'রোল: ' . htmlspecialchars($receipt_data['roll_number']); ?><br>
                <?php echo 'ক্লাস: ' . htmlspecialchars($receipt_data['class_name'] . ' - ' . $receipt_data['section']); ?><br>
                <?php echo 'সেশন: ' . htmlspecialchars($receipt_data['session'] ?? $receipt_data['academic_year']); ?>
            </div>

            <!-- Center: Institution from bank_receipt_settings -->
            <div class="header-center">
                <?php if (!empty($receipt_settings['school_name'])): ?>
                    <h3><?php echo htmlspecialchars($receipt_settings['school_name']); ?></h3>
                <?php endif; ?>
                <?php if (!empty($receipt_settings['address'])): ?>
                    <p><?php echo nl2br(htmlspecialchars($receipt_settings['address'])); ?></p>
                <?php endif; ?>
                <?php if (!empty($receipt_settings['subtitle'])): ?>
                    <p class="receipt-subtitle"><?php echo htmlspecialchars($receipt_settings['subtitle']); ?></p>
                <?php endif; ?>
                <div class="memo-title-badge"><?php echo htmlspecialchars($receipt_settings['receipt_title']); ?></div>
            </div>

            <!-- Right: Receipt number & date -->
            <div class="header-right">
                <div class="header-label">রসিদ তথ্য</div>
                <strong>রসিদ নং:</strong> <?php echo htmlspecialchars($receipt_data['payment_id']); ?><br>
                <strong>টিআইডি:</strong> <span class="txn-id"><?php echo htmlspecialchars($receipt_data['transaction_id'] ?? 'N/A'); ?></span><br>
                <strong>তারিখ:</strong> <?php echo date("d M, Y", strtotime($receipt_data['payment_date'])); ?>, <span id="current-time"></span>
            </div>

        </div>
        <!-- end 3-col header -->

        <table class="table table-bordered memo-table">
            <thead class="table-light">
                <tr>
                    <th>বিবরণ</th>
                    <th class="text-end">টাকা</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <?php
                            echo htmlspecialchars($receipt_data['fee_type']);
                            if ($receipt_data['month']) {
                                echo " - " . htmlspecialchars($receipt_data['month']);
                            }
                        ?>
                    </td>
                    <td class="text-end"><strong><?php echo number_format($receipt_data['amount'], 2); ?></strong></td>
                </tr>
            </tbody>
        </table>

        <div class="memo-footer">
            <div>
                <p class="amount-in-words"><?php echo numberToWordsBengali($receipt_data['amount']); ?></p>
                <p><strong>পেমেন্ট মাধ্যম:</strong> <?php echo htmlspecialchars(ucfirst($receipt_data['payment_method'])); ?></p>
            </div>
            <div class="signature-area">
                <div class="line"></div>
                <p>আদায়কারীর স্বাক্ষর</p>
            </div>
        </div>
    </div>

    <div class="text-center mt-3 no-print">
        <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
        <button class="btn btn-primary" onclick="openCustomizeModal()"><i class="fas fa-sliders-h"></i> কাস্টমাইজ</button>
        <a href="receipt.php" class="btn btn-secondary"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
    </div>
</div>

<!-- Customize Panel (draggable, compact) -->
<div id="customizePanel" class="no-print" style="display:none; position:fixed; top:80px; right:20px; width:280px; background:#fff; border:1px solid #ccc; border-radius:10px; box-shadow:0 4px 20px rgba(0,0,0,0.2); z-index:9999; font-size:0.82rem;">
    <div id="customizePanelHeader" style="background:linear-gradient(135deg,#667eea,#764ba2); color:#fff; padding:8px 12px; border-radius:10px 10px 0 0; cursor:move; display:flex; justify-content:space-between; align-items:center; user-select:none;">
        <span><i class="fas fa-sliders-h"></i> কাস্টমাইজ</span>
        <button onclick="document.getElementById('customizePanel').style.display='none'" style="background:none;border:none;color:#fff;font-size:1rem;cursor:pointer;padding:0;">&times;</button>
    </div>
    <div style="padding:10px 12px; max-height:70vh; overflow-y:auto;">
        <div class="mb-2">
            <label class="fw-bold d-block mb-1">ফন্ট</label>
            <select class="form-select form-select-sm" id="fontSelect">
                <option value="'Hind Siliguri', sans-serif" <?php echo $display_settings['receipt_font'] === "'Hind Siliguri', sans-serif" ? 'selected' : ''; ?>>Hind Siliguri</option>
                <option value="'Noto Sans Bengali', sans-serif" <?php echo $display_settings['receipt_font'] === "'Noto Sans Bengali', sans-serif" ? 'selected' : ''; ?>>Noto Sans Bengali</option>
                <option value="'Kalpurush', sans-serif" <?php echo $display_settings['receipt_font'] === "'Kalpurush', sans-serif" ? 'selected' : ''; ?>>Kalpurush</option>
                <option value="Arial, sans-serif" <?php echo $display_settings['receipt_font'] === "Arial, sans-serif" ? 'selected' : ''; ?>>Arial</option>
                <option value="'Times New Roman', serif" <?php echo $display_settings['receipt_font'] === "'Times New Roman', serif" ? 'selected' : ''; ?>>Times New Roman</option>
            </select>
        </div>
        <div class="mb-2">
            <label class="fw-bold">ফন্ট সাইজ: <span id="fontSizeVal"><?php echo (int)$display_settings['receipt_font_size']; ?></span>px</label>
            <input type="range" class="form-range" id="fontSizeRange" min="10" max="20" value="<?php echo (int)$display_settings['receipt_font_size']; ?>">
        </div>
        <hr class="my-2">
        <div class="mb-2">
            <label class="fw-bold d-block mb-1">ওয়াটারমার্ক টেক্সট</label>
            <input type="text" class="form-control form-control-sm" id="wmText" value="<?php echo htmlspecialchars($display_settings['receipt_wm_text']); ?>">
        </div>
        <div class="mb-2 d-flex gap-2 align-items-center">
            <div>
                <label class="fw-bold d-block mb-1">রঙ</label>
                <input type="color" class="form-control form-control-color form-control-sm" id="wmColor" value="<?php echo htmlspecialchars($display_settings['receipt_wm_color']); ?>" style="width:40px;height:30px;padding:2px;">
            </div>
            <div class="flex-grow-1">
                <label class="fw-bold">অপাসিটি: <span id="wmOpacityVal"><?php echo (int)$display_settings['receipt_wm_opacity']; ?></span>%</label>
                <input type="range" class="form-range" id="wmOpacity" min="0" max="40" value="<?php echo (int)$display_settings['receipt_wm_opacity']; ?>">
            </div>
        </div>
        <div class="mb-2">
            <label class="fw-bold">সাইজ: <span id="wmSizeVal"><?php echo (int)$display_settings['receipt_wm_size']; ?></span>rem</label>
            <input type="range" class="form-range" id="wmSize" min="3" max="15" value="<?php echo (int)$display_settings['receipt_wm_size']; ?>">
        </div>
        <div class="d-flex gap-2 mt-2">
            <button class="btn btn-sm btn-secondary flex-fill" onclick="resetCustomize()"><i class="fas fa-undo"></i> রিসেট</button>
            <button class="btn btn-sm btn-success flex-fill" id="saveBtn" onclick="saveSettings()"><i class="fas fa-save"></i> সেভ</button>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Current time
    function updateTime() {
        const now = new Date();
        let h = now.getHours();
        const m = String(now.getMinutes()).padStart(2, '0');
        const ampm = h >= 12 ? 'PM' : 'AM';
        h = h % 12 || 12;
        const el = document.getElementById('current-time');
        if (el) el.textContent = h + ':' + m + ' ' + ampm;
    }
    updateTime();

    function openCustomizeModal() {
        const p = document.getElementById('customizePanel');
        p.style.display = p.style.display === 'none' ? 'block' : 'none';
    }

    // Drag logic
    (function() {
        const panel = document.getElementById('customizePanel');
        const header = document.getElementById('customizePanelHeader');
        if (!panel || !header) return;
        let isDragging = false, startX, startY, origLeft, origTop;
        header.addEventListener('mousedown', function(e) {
            if (e.target.tagName === 'BUTTON') return;
            isDragging = true;
            const rect = panel.getBoundingClientRect();
            startX = e.clientX; startY = e.clientY;
            origLeft = rect.left; origTop = rect.top;
            panel.style.right = 'auto';
            panel.style.left = origLeft + 'px';
            panel.style.top  = origTop  + 'px';
            document.body.style.userSelect = 'none';
        });
        document.addEventListener('mousemove', function(e) {
            if (!isDragging) return;
            panel.style.left = (origLeft + e.clientX - startX) + 'px';
            panel.style.top  = (origTop  + e.clientY - startY) + 'px';
        });
        document.addEventListener('mouseup', function() {
            isDragging = false;
            document.body.style.userSelect = '';
        });
    })();
    // Customize helpers
    function applyFont() {
        const font = document.getElementById('fontSelect').value;
        const size = document.getElementById('fontSizeRange').value;
        document.querySelector('.memo-box').style.fontFamily = font;
        document.querySelector('.memo-box').style.fontSize = size + 'px';
    }

    function applyWatermark() {
        const wm = document.querySelector('.paid-watermark');
        if (!wm) return;
        const text    = document.getElementById('wmText').value;
        const color   = document.getElementById('wmColor').value;
        const opacity = document.getElementById('wmOpacity').value / 100;
        const size    = document.getElementById('wmSize').value;
        wm.textContent = text;
        wm.style.color = hexToRgba(color, opacity);
        wm.style.fontSize = size + 'rem';
    }

    function hexToRgba(hex, alpha) {
        const r = parseInt(hex.slice(1,3),16);
        const g = parseInt(hex.slice(3,5),16);
        const b = parseInt(hex.slice(5,7),16);
        return `rgba(${r},${g},${b},${alpha})`;
    }

    function resetCustomize() {
        document.getElementById('fontSelect').value = "'Hind Siliguri', sans-serif";
        document.getElementById('fontSizeRange').value = 14;
        document.getElementById('fontSizeVal').textContent = 14;
        document.getElementById('wmText').value = '<?php echo htmlspecialchars($display_settings['receipt_wm_text']); ?>';
        document.getElementById('wmColor').value = '#008000';
        document.getElementById('wmOpacity').value = 7;
        document.getElementById('wmOpacityVal').textContent = 7;
        document.getElementById('wmSize').value = 8;
        document.getElementById('wmSizeVal').textContent = 8;
        applyFont(); applyWatermark();
    }

    function saveSettings() {
        const btn = document.getElementById('saveBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> সেভ হচ্ছে...';

        const data = new FormData();
        data.append('ajax', 'save_display_settings');
        data.append('receipt_font',       document.getElementById('fontSelect').value);
        data.append('receipt_font_size',  document.getElementById('fontSizeRange').value);
        data.append('receipt_wm_text',    document.getElementById('wmText').value);
        data.append('receipt_wm_color',   document.getElementById('wmColor').value);
        data.append('receipt_wm_opacity', document.getElementById('wmOpacity').value);
        data.append('receipt_wm_size',    document.getElementById('wmSize').value);

        fetch('', { method: 'POST', body: data })
            .then(r => r.json())
            .then(res => {
                btn.disabled = false;
                if (res.success) {
                    btn.innerHTML = '<i class="fas fa-check"></i> সেভ হয়েছে';
                    btn.classList.replace('btn-success', 'btn-outline-success');
                    setTimeout(() => {
                        btn.innerHTML = '<i class="fas fa-save"></i> সেভ করুন';
                        btn.classList.replace('btn-outline-success', 'btn-success');
                    }, 2000);
                } else {
                    btn.innerHTML = '<i class="fas fa-times"></i> ত্রুটি হয়েছে';
                }
            })
            .catch(() => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-times"></i> ত্রুটি হয়েছে';
            });
    }

    // Live preview on input change
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('fontSelect').addEventListener('change', applyFont);

        document.getElementById('fontSizeRange').addEventListener('input', function () {
            document.getElementById('fontSizeVal').textContent = this.value;
            applyFont();
        });
        document.getElementById('wmText').addEventListener('input', applyWatermark);
        document.getElementById('wmColor').addEventListener('input', applyWatermark);
        document.getElementById('wmOpacity').addEventListener('input', function () {
            document.getElementById('wmOpacityVal').textContent = this.value;
            applyWatermark();
        });
        document.getElementById('wmSize').addEventListener('input', function () {
            document.getElementById('wmSizeVal').textContent = this.value;
            applyWatermark();
        });
    });
</script>
</body>
</html>
