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

if (!isset($_SESSION["user_id"]) || !in_array($_SESSION["role"], ["customer","company_admin"])) {
    header("Location: ../auth/login.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM customers WHERE user_id = ? LIMIT 1");
$stmt->execute([$_SESSION["user_id"]]);
$sender = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sender) {
    die("No customer wallet connected.");
}

/* AJAX: resolve a receiver code -> name (so the app can show who you're paying). */
if (isset($_GET["lookup"])) {
    header('Content-Type: application/json');
    $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', (string)$_GET["lookup"]));
    $out = ['found'=>false, 'self'=>false, 'name'=>'', 'code'=>$code];
    if ($code !== '') {
        $q = $pdo->prepare("SELECT customer_code, full_name FROM customers WHERE customer_code=? AND status='active' LIMIT 1");
        $q->execute([$code]);
        if ($r = $q->fetch(PDO::FETCH_ASSOC)) {
            if ($r['customer_code'] === $sender['customer_code']) { $out['self'] = true; }
            else { $out = ['found'=>true, 'self'=>false, 'name'=>(string)($r['full_name'] ?? ''), 'code'=>(string)$r['customer_code']]; }
        }
    }
    echo json_encode($out); exit;
}

$prefill_receiver_code = isset($_GET["to"]) ? trim($_GET["to"]) : "";

$error = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $receiver_code = trim($_POST["receiver_code"]);
    $amount = floatval(str_replace(',', '', $_POST["amount"]));
    $note = trim($_POST["note"]);

    // Tolerate QR scans that return a URL or have a ?to= parameter or stray characters
    if (stripos($receiver_code, 'http') === 0 || strpos($receiver_code, '?to=') !== false) {
        $parts = parse_url($receiver_code);
        if (!empty($parts['query'])) {
            parse_str($parts['query'], $qs);
            if (!empty($qs['to'])) {
                $receiver_code = $qs['to'];
            }
        }
        if (stripos($receiver_code, 'http') === 0 && !empty($parts['path'])) {
            $receiver_code = basename($parts['path']);
        }
    }
    // Keep only valid code characters (letters, digits) — removes spaces, newlines, etc.
    $receiver_code = preg_replace('/[^A-Za-z0-9]/', '', $receiver_code);
    $receiver_code = strtoupper($receiver_code);

    $stmt = $pdo->prepare("
        SELECT *
        FROM customers
        WHERE customer_code = ? AND status = 'active'
        LIMIT 1
    ");
    $stmt->execute([$receiver_code]);
    $receiver = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$receiver) {
        $error = "Receiver customer not found.";
    } elseif ($receiver["id"] == $sender["id"]) {
        $error = "You cannot transfer to yourself.";
    } elseif ($amount <= 0) {
        $error = "Amount must be greater than zero.";
    } elseif ($amount > $sender["balance"]) {
        $error = "Not enough balance.";
    } else {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("
                UPDATE customers
                SET balance = balance - ?
                WHERE id = ?
            ");
            $stmt->execute([$amount, $sender["id"]]);

            $stmt = $pdo->prepare("
                UPDATE customers
                SET balance = balance + ?
                WHERE id = ?
            ");
            $stmt->execute([$amount, $receiver["id"]]);

            $transaction_code = "CTX" . time();

            $stmt = $pdo->prepare("
                INSERT INTO customer_transfers
                (
                    transaction_code,
                    sender_customer_id,
                    receiver_customer_id,
                    amount,
                    note
                )
                VALUES (?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $transaction_code,
                $sender["id"],
                $receiver["id"],
                $amount,
                $note
            ]);
            $stmt = $pdo->prepare("
                INSERT INTO transactions
                (
                    from_type,
                    from_id,
                    to_type,
                    to_id,
                    amount,
                    customer_read_at,
                    created_at
                )
                VALUES
                (
                    'customer',
                    ?,
                    'customer',
                    ?,
                    ?,
                    NULL,
                    NOW()
                )
            ");
            $stmt->execute([
                $sender["id"],
                $receiver["id"],
                $amount
            ]);

            $pdo->commit();

            require_once __DIR__ . '/../config/notify.php';
            notify_money_received($pdo, (int)$receiver["id"], (float)$amount, $sender["full_name"] ?? "");

            $success = "Transfer successful.";
            $sentAmount = $amount;
            $prefill_receiver_code = $receiver_code;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}

$stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ? LIMIT 1");
$stmt->execute([$sender["id"]]);
$sender = $stmt->fetch(PDO::FETCH_ASSOC);

/* resolve receiver name for prefilled / just-sent code */
$receiverName = "";
if ($prefill_receiver_code !== "") {
    $rc = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $prefill_receiver_code));
    $q = $pdo->prepare("SELECT full_name FROM customers WHERE customer_code=? AND status='active' LIMIT 1");
    $q->execute([$rc]);
    $receiverName = (string)($q->fetchColumn() ?: "");
}
function initials($name){ $name=trim((string)$name); if($name==='') return '👤'; $p=preg_split('/\s+/',$name); $a=mb_substr($p[0],0,1); $b=count($p)>1?mb_substr(end($p),0,1):''; return mb_strtoupper($a.$b); }
function e2($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
$senderName = (string)($sender["full_name"] ?? "");
$balance    = (float)$sender["balance"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
<title>Transfer</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
:root{--red:#b91c1c;--red2:#7f1d1d;--bg:#f1f5f9;--card:#fff;--ink:#0f172a;--muted:#64748b;--line:#e6eaf2;--green:#16a34a;}
body{font-family:'Noto Sans Lao','Inter',Arial,sans-serif;background:var(--bg);color:var(--ink);min-height:100vh;}
.screen{max-width:520px;margin:0 auto;min-height:100vh;display:flex;flex-direction:column;background:var(--bg);}
.hdr{background:linear-gradient(135deg,var(--red),var(--red2));color:#fff;padding:calc(14px + env(safe-area-inset-top,0px)) 16px 16px;display:flex;align-items:center;gap:12px;position:sticky;top:0;z-index:20;}
.hdr .back{width:38px;height:38px;border-radius:10px;background:rgba(255,255,255,.18);color:#fff;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:20px;flex:0 0 auto;}
.hdr .htitle{font-size:18px;font-weight:800;}
.body{flex:1;padding:16px;display:flex;flex-direction:column;gap:14px;padding-bottom:120px;}
.flash{padding:13px 15px;border-radius:12px;font-weight:700;font-size:14px;}
.flash.ok{background:#dcfce7;color:#166534;border:1px solid #86efac;}
.flash.err{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5;}
.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:16px;box-shadow:0 2px 10px rgba(15,23,42,.05);}
.lbl{font-size:11px;font-weight:800;letter-spacing:.05em;text-transform:uppercase;color:var(--muted);margin-bottom:10px;}
.acct-row{display:flex;align-items:center;gap:12px;}
.avatar{width:46px;height:46px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:16px;color:#fff;flex:0 0 auto;}
.avatar.sender{background:#2563eb;}
.avatar.recv{background:var(--green);}
.acct-info .nm{font-size:15px;font-weight:800;line-height:1.2;}
.acct-info .sub{font-size:12.5px;color:var(--muted);margin-top:3px;}
.acct-info .sub b{color:var(--ink);}
.code-input{display:flex;gap:8px;margin-top:12px;}
.code-input input{flex:1;padding:13px 14px;border:1.5px solid var(--line);border-radius:11px;font-size:16px;font-family:inherit;letter-spacing:.03em;text-transform:uppercase;}
.code-input input:focus{outline:none;border-color:var(--red);}
.hint{font-size:12px;color:var(--muted);margin-top:8px;}
.hint.bad{color:#dc2626;font-weight:700;}
.hint.good{color:var(--green);font-weight:700;}
.amount-card{text-align:center;padding:22px 16px;}
.amount-display{display:flex;align-items:center;justify-content:center;gap:8px;margin:6px 0 4px;}
.amount-display input{width:100%;max-width:300px;border:none;text-align:center;font-size:44px;font-weight:800;color:var(--ink);font-family:inherit;background:transparent;padding:0;}
.amount-display input:focus{outline:none;}
.amount-display .cur{font-size:22px;font-weight:800;color:var(--muted);}
.bal-line{font-size:12.5px;color:var(--muted);}
.bal-line b{color:var(--ink);}
.chips{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin-top:16px;}
.chip{border:1.5px solid var(--line);background:#f8fafc;color:#334155;border-radius:999px;padding:8px 14px;font-size:13px;font-weight:800;cursor:pointer;font-family:inherit;}
.chip:hover,.chip:active{border-color:var(--red);color:var(--red);}
textarea{width:100%;padding:13px 14px;border:1.5px solid var(--line);border-radius:11px;font-size:15px;font-family:inherit;min-height:70px;resize:vertical;}
textarea:focus{outline:none;border-color:var(--red);}
.footer{position:fixed;left:0;right:0;bottom:0;background:#fff;border-top:1px solid var(--line);padding:12px 16px calc(12px + env(safe-area-inset-bottom,0px));z-index:20;}
.footer-in{max-width:520px;margin:0 auto;}
.btn-go{width:100%;padding:16px;border:none;border-radius:14px;background:var(--red);color:#fff;font-size:17px;font-weight:800;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px;}
.btn-go:disabled{background:#cbd5e1;cursor:not-allowed;}
.btn-go .sum{opacity:.85;font-weight:700;font-size:14px;}
</style>
</head>
<body>
<div class="screen">
    <header class="hdr">
        <a class="back" href="dashboard.php" onclick="if(document.referrer){history.back();return false;}">&larr;</a>
        <div class="htitle" data-lo="ໂອນເງິນ" data-en="Transfer">Transfer</div>
    </header>

    <form method="POST" id="xferForm">
    <div class="body">

        <?php if ($success): ?>
            <div class="flash ok">✅ <?= e2($success) ?><?php if(!empty($sentAmount)): ?> — <?= number_format($sentAmount,0) ?> ₭ sent to <?= e2($receiverName ?: $prefill_receiver_code) ?>.<?php endif; ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="flash err">⚠️ <?= e2($error) ?></div>
        <?php endif; ?>

        <!-- From -->
        <div class="card">
            <div class="lbl" data-lo="ຈາກ" data-en="From">From</div>
            <div class="acct-row">
                <div class="avatar sender"><?= e2(initials($senderName)) ?></div>
                <div class="acct-info">
                    <div class="nm"><?= $senderName!=='' ? e2($senderName) : 'Your wallet' ?></div>
                    <div class="sub"><?= e2($sender["customer_code"]) ?> · <span data-lo="ຍອດເງິນ" data-en="Balance">Balance</span> <b id="balTxt"><?= number_format($balance,0) ?> ₭</b></div>
                </div>
            </div>
        </div>

        <!-- To -->
        <div class="card">
            <div class="lbl" data-lo="ຫາ" data-en="To">To</div>
            <div class="acct-row" id="toRow" style="display:<?= $receiverName!=='' ? 'flex' : 'none' ?>;">
                <div class="avatar recv" id="toAvatar"><?= e2(initials($receiverName)) ?></div>
                <div class="acct-info">
                    <div class="nm" id="toName"><?= e2($receiverName) ?></div>
                    <div class="sub" id="toCodeTxt"><?= e2($prefill_receiver_code) ?></div>
                </div>
            </div>
            <div class="code-input">
                <input type="text" id="rcode" name="receiver_code" placeholder="Customer code (e.g. ST000037)"
                       value="<?= e2($prefill_receiver_code) ?>" autocomplete="off" required>
            </div>
            <div class="hint" id="rhint" data-lo="ໃສ່ລະຫັດລູກຄ້າ ຫຼື ສະແກນ QR." data-en="Enter customer code or scan their QR.">Enter customer code or scan their QR.</div>
        </div>

        <!-- Amount -->
        <div class="card amount-card">
            <div class="lbl" data-lo="ຈຳນວນເງິນ (ກີບ)" data-en="Amount (LAK)">Amount (LAK)</div>
            <div class="amount-display">
                <input type="text" id="amount" name="amount" inputmode="numeric" placeholder="0" autocomplete="off" required>
                <span class="cur">₭</span>
            </div>
            <div class="bal-line"><span data-lo="ໃຊ້ໄດ້" data-en="Available">Available</span>: <b><?= number_format($balance,0) ?> ₭</b></div>
            <div class="chips">
                <?php foreach ([1000,5000,10000,50000,100000] as $amt): ?>
                    <button type="button" class="chip" data-amt="<?= $amt ?>"><?= number_format($amt,0) ?></button>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Note -->
        <div class="card">
            <div class="lbl" data-lo="ໝາຍເຫດ (ບໍ່ບັງຄັບ)" data-en="Note (optional)">Note (optional)</div>
            <textarea name="note" placeholder="Optional note"></textarea>
        </div>

    </div>

    <div class="footer">
        <div class="footer-in">
            <button type="submit" class="btn-go" id="goBtn" disabled>
                <span data-lo="ໂອນເງິນ" data-en="Transfer">Transfer</span>
                <span class="sum" id="goSum"></span>
            </button>
        </div>
    </div>
    </form>
</div>

<script>
var BAL = <?= json_encode($balance) ?>;
var rcode  = document.getElementById('rcode');
var amount = document.getElementById('amount');
var goBtn  = document.getElementById('goBtn');
var goSum  = document.getElementById('goSum');
var rhint  = document.getElementById('rhint');
var toRow  = document.getElementById('toRow');
var toName = document.getElementById('toName');
var toCode = document.getElementById('toCodeTxt');
var toAv   = document.getElementById('toAvatar');
var recvOK = <?= $receiverName!=='' ? 'true' : 'false' ?>;

function fmt(n){ return Number(n).toLocaleString('en-US'); }
function amtValue(){ return parseInt((amount.value||'').replace(/[^\d]/g,''),10) || 0; }
function ini(name){ name=(name||'').trim(); if(!name) return '👤'; var p=name.split(/\s+/); return (p[0].charAt(0)+(p.length>1?p[p.length-1].charAt(0):'')).toUpperCase(); }

function refresh(){
    var a = amtValue();
    var okAmt = a>0 && a<=BAL;
    var okRcv = recvOK && rcode.value.trim().length>0;
    goBtn.disabled = !(okAmt && okRcv);
    goSum.textContent = a>0 ? ('· '+fmt(a)+' ₭') : '';
    // amount over balance warning
}

// Amount formatting + validation
amount.addEventListener('input', function(){
    var v = this.value.replace(/[^\d]/g,'');
    this.value = v==='' ? '' : fmt(v);
    var a = amtValue();
    if (a>BAL) { this.style.color='#dc2626'; } else { this.style.color=''; }
    refresh();
});

// Quick chips set the amount
document.querySelectorAll('.chip').forEach(function(c){
    c.addEventListener('click', function(){
        amount.value = fmt(this.getAttribute('data-amt'));
        amount.dispatchEvent(new Event('input'));
        amount.focus();
    });
});

// Receiver lookup (debounced)
var t=null;
function lookup(){
    var code = rcode.value.trim();
    recvOK=false; refresh();
    if (code.length < 3){ toRow.style.display='none'; rhint.className='hint'; rhint.textContent='Enter customer code or scan their QR.'; return; }
    fetch('transfer.php?lookup='+encodeURIComponent(code))
        .then(function(r){return r.json();})
        .then(function(d){
            if (d.self){ toRow.style.display='none'; rhint.className='hint bad'; rhint.textContent="That's your own code."; recvOK=false; }
            else if (d.found){
                toName.textContent = d.name || d.code;
                toCode.textContent = d.code;
                toAv.textContent = ini(d.name);
                toRow.style.display='flex';
                rhint.className='hint good'; rhint.textContent='✓ '+(d.name||d.code);
                recvOK=true;
            } else {
                toRow.style.display='none'; rhint.className='hint bad'; rhint.textContent='Customer not found.'; recvOK=false;
            }
            refresh();
        }).catch(function(){});
}
rcode.addEventListener('input', function(){ clearTimeout(t); t=setTimeout(lookup, 350); });

// strip commas before submit
document.getElementById('xferForm').addEventListener('submit', function(){
    amount.value = amount.value.replace(/,/g,'');
});

if (recvOK) refresh();
</script>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>