<?php
/**
 * includes/payment_section.php
 *
 * Renders the full payment section:
 *   - Payment history table (loaded via AJAX)
 *   - Payment method selector (CASH / EFT)
 *   - EFT proof upload (file or camera)
 *   - Cash amount entry
 *   - "Send Payment" button
 *
 * Required before including:
 *   $jc_no    (string|int) — the jobcard number used by payment endpoints
 *   $user_id  (int)        — current logged-in user ID  ($_SESSION['user_id'])
 *
 * Optional:
 *   $payment_section_title (string) — heading text, defaults to 'PAYMENTS'
 *
 * Usage:
 *   $jc_no   = $record['jc_no'];
 *   $user_id = intval($_SESSION['user_id']);
 *   include '../../includes/payment_section.php';
 */

if (!isset($jc_no) || !isset($user_id)) {
    trigger_error('payment_section.php requires $jc_no and $user_id to be set.', E_USER_WARNING);
    return;
}

$jc_no    = htmlspecialchars((string)$jc_no, ENT_QUOTES);
$user_id  = intval($user_id);
$title    = isset($payment_section_title) ? htmlspecialchars($payment_section_title) : 'PAYMENTS';
?>

<div class="payment-section" style="padding:2vw;background-color:navy;width:100%;box-sizing:border-box;">

    <h2 style="color:white;" class="heading_h2"><?= $title ?></h2>

    <!-- Payment history (loaded on mount) -->
    <div id="payment_history_table"
         style="display:flex;flex-direction:column;width:98%;justify-content:center;padding:1vw;background:whitesmoke;">
    </div>

    <!-- Payment form -->
    <div id="payment_form_wrap"
         style="display:flex;flex-direction:column;width:100%;align-items:center;background:whitesmoke;padding:1vw;">

        <label class="big_labels">PAYMENT TYPE</label>
        <select id="pmt_method" name="payment_method" class="big_inputs"
                style="width:90%;" onchange="pmt_onMethodChange()">
            <option value="">-- Select --</option>
            <option value="CASH">CASH</option>
            <option value="EFT">EFT</option>
        </select>

        <!-- EFT options (hidden until EFT is selected) -->
        <div id="pmt_eft_wrap" style="display:none;flex-direction:column;align-items:center;width:100%;">

            <label class="big_labels">PROOF TYPE</label>
            <select id="pmt_eft_type" class="big_inputs" style="width:90%;"
                    onchange="pmt_onEftTypeChange()">
                <option value="">-- Select --</option>
                <option value="FILE">ATTACH FILE</option>
                <option value="CAMERA">OPEN CAMERA</option>
            </select>

            <!-- File attach -->
            <div id="pmt_file_div" style="display:none;flex-direction:column;align-items:center;width:100%;">
                <label class="big_labels">Insert Payment Proof</label>
                <input type="file" id="pmt_proof_file" name="payment_proof"
                       style="width:90%;" class="big_inputs"
                       onchange="pmt_uploadFile()">
                <input type="hidden" id="pmt_uploaded_filename" value="">
            </div>

            <!-- Camera capture -->
            <div id="pmt_camera_div" style="display:none;flex-direction:column;align-items:center;width:100%;">
                <video id="pmt_cam_video"
                       style="display:none;width:400px;height:300px;border:3px solid #ccc;border-radius:2vw;margin-top:10px;"
                       autoplay playsinline></video>

                <button id="pmt_cam_open" class="submit_btn"
                        onclick="PmtCam.open()">Open Camera</button>

                <div id="pmt_cam_load" style="display:none;width:100%;justify-content:center;">
                    <button class="submit_btn" onclick="PmtCam.capture()">Capture Photo</button>
                    <button class="submit_btn" onclick="PmtCam.stop()">Stop Camera</button>
                </div>

                <canvas id="pmt_cam_snap"
                        style="display:none;width:400px;height:300px;border:3px solid #ccc;border-radius:2vw;margin-top:10px;"></canvas>

                <input type="hidden" id="pmt_slip_file" name="slip_file" value="">
            </div>

        </div><!-- #pmt_eft_wrap -->

        <!-- Cash amount (shown for CASH and EFT) -->
        <div id="pmt_cash_wrap" style="display:none;flex-direction:column;align-items:center;width:100%;">
            <label class="big_labels">AMOUNT</label>
            <input type="number" id="pmt_amount" name="cash_amount"
                   placeholder="Amount" class="big_inputs" style="width:90%;">
            <button class="submit_btn" style="width:90%;margin-top:1vw;"
                    onclick="pmt_submit()">SEND PAYMENT</button>
        </div>

    </div><!-- #payment_form_wrap -->

</div><!-- .payment-section -->

<script>
(function () {

    var JC_NO   = '<?= $jc_no ?>';
    var USER_ID = '<?= $user_id ?>';

    /* ── Method toggle ──────────────────────────────────── */
    window.pmt_onMethodChange = function () {
        var v  = document.getElementById('pmt_method').value;
        var ew = document.getElementById('pmt_eft_wrap');
        var cw = document.getElementById('pmt_cash_wrap');
        ew.style.display = (v === 'EFT')              ? 'flex' : 'none';
        cw.style.display = (v === 'EFT' || v === 'CASH') ? 'flex' : 'none';
    };

    /* ── EFT type toggle ────────────────────────────────── */
    window.pmt_onEftTypeChange = function () {
        var v  = document.getElementById('pmt_eft_type').value;
        var fd = document.getElementById('pmt_file_div');
        var cd = document.getElementById('pmt_camera_div');
        fd.style.display = (v === 'FILE')   ? 'flex' : 'none';
        cd.style.display = (v === 'CAMERA') ? 'flex' : 'none';
    };

    /* ── Camera for EFT slip ────────────────────────────── */
    window.PmtCam = (function () {
        var _stream = null;
        return {
            open: function () {
                navigator.mediaDevices
                    .getUserMedia({ video: { facingMode: 'environment' }, audio: false })
                    .then(function (s) {
                        _stream = s;
                        var v = document.getElementById('pmt_cam_video');
                        v.srcObject = s; v.style.display = 'block';
                        document.getElementById('pmt_cam_load').style.display = 'flex';
                        document.getElementById('pmt_cam_open').style.display = 'none';
                    })
                    .catch(function (e) { alert('Camera error: ' + e.message); });
            },
            stop: function () {
                if (_stream) { _stream.getTracks().forEach(function (t) { t.stop(); }); _stream = null; }
                var v = document.getElementById('pmt_cam_video');
                v.srcObject = null; v.style.display = 'none';
                document.getElementById('pmt_cam_load').style.display = 'none';
                document.getElementById('pmt_cam_open').style.display = 'block';
            },
            capture: function () {
                var video  = document.getElementById('pmt_cam_video');
                var canvas = document.getElementById('pmt_cam_snap');
                var ctx    = canvas.getContext('2d');
                canvas.width  = video.videoWidth;
                canvas.height = video.videoHeight;
                ctx.drawImage(video, 0, 0);
                this.stop();

                var fd = new FormData();
                fd.append('image',        canvas.toDataURL('image/png'));
                fd.append('jobcard_no',   JC_NO);
                fd.append('folder_path',  '../jobcards/slips/');
                fd.append('section_name', 'slip');

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '../jobcards/save_camera.php', true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState !== 4 || xhr.status !== 200) return;
                    var r = xhr.responseText.trim();
                    if (r && r !== '0') {
                        document.getElementById('pmt_slip_file').value = r;
                        alert('Slip photo saved!');
                    } else {
                        alert('Error saving photo.');
                    }
                };
                xhr.send(fd);
            }
        };
    }());

    /* ── File upload ────────────────────────────────────── */
    window.pmt_uploadFile = function () {
        var file = document.getElementById('pmt_proof_file').files[0];
        if (!file) return;

        var fd = new FormData();
        fd.append('file',           file);
        fd.append('jobcard_no',     JC_NO);
        fd.append('ajax_type',      'lead_payment_slip');
        fd.append('section_name',   'slip');
        fd.append('file_save_path', '../jobcards/slips/');

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) return;
            if (xhr.status === 200 && xhr.responseText.includes('OK')) {
                var filename = xhr.responseText.replace('OK | ', '').trim();
                document.getElementById('pmt_uploaded_filename').value = filename;
                alert('File uploaded successfully!');
            } else {
                alert('Upload failed. Try again.');
            }
        };
        xhr.open('POST', '../jobcards/upload_slip.php', true);
        xhr.send(fd);
    };

    /* ── Submit payment ─────────────────────────────────── */
    window.pmt_submit = function () {
        var method   = document.getElementById('pmt_method').value;
        var eft_type = document.getElementById('pmt_eft_type').value;
        var amount   = document.getElementById('pmt_amount').value;

        if (!method) { alert('Please select a payment method.'); return; }
        if (!amount || isNaN(amount) || parseFloat(amount) <= 0) {
            alert('Please enter a valid amount.');
            return;
        }

        var fd = new FormData();
        fd.append('record_id',      JC_NO);
        fd.append('payment_method', method);
        fd.append('amount',         amount);
        fd.append('user_id',        USER_ID);

        if (method === 'EFT') {
            if (eft_type === 'CAMERA') {
                var slip = document.getElementById('pmt_slip_file').value;
                if (!slip.trim()) { alert('Please capture a slip image.'); return; }
                fd.append('file', slip);
            } else if (eft_type === 'FILE') {
                var fname = document.getElementById('pmt_uploaded_filename').value;
                if (!fname) { alert('Please upload a proof file.'); return; }
                fd.append('file', fname);
            } else {
                alert('Please select how to provide payment proof.');
                return;
            }
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '../jobcards/jobcard_payments.ajax.php', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) return;
            if (xhr.status === 200 && xhr.responseText.includes('OK')) {
                alert('Payment completed successfully!');
                pmt_resetForm();
                pmt_loadHistory();
            } else {
                alert('Payment error. Try again.\n' + xhr.responseText);
            }
        };
        xhr.send(fd);
    };

    /* ── Reset form after successful payment ────────────── */
    function pmt_resetForm() {
        document.getElementById('pmt_method').selectedIndex   = 0;
        document.getElementById('pmt_eft_type').selectedIndex = 0;
        document.getElementById('pmt_amount').value           = '';
        document.getElementById('pmt_slip_file').value        = '';
        document.getElementById('pmt_uploaded_filename').value = '';
        var pf = document.getElementById('pmt_proof_file');
        if (pf) pf.value = '';
        document.getElementById('pmt_eft_wrap').style.display  = 'none';
        document.getElementById('pmt_cash_wrap').style.display = 'none';
        document.getElementById('pmt_file_div').style.display  = 'none';
        document.getElementById('pmt_camera_div').style.display = 'none';
        PmtCam.stop();
    }

    /* ── Load payment history ───────────────────────────── */
    window.pmt_loadHistory = function () {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                document.getElementById('payment_history_table').innerHTML = xhr.responseText;
            }
        };
        xhr.open('POST', '../jobcards/payment_history.ajax.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('jobcard_no=' + encodeURIComponent(JC_NO));
    };

    /* Load history on first render */
    document.addEventListener('DOMContentLoaded', window.pmt_loadHistory);
    window.pmt_loadHistory();

}());
</script>