<?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.");
}

$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();

            $success = "Transfer successful.";
            $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);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Customer Transfer</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 30px;
        }

        .container {
            max-width: 820px;
            margin: auto;
        }

        .card {
            background: white;
            border-radius: 16px;
            padding: 28px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.08);
        }

        h1 {
            margin-top: 0;
            color: #111827;
        }

        .subtitle {
            color: #6b7280;
            margin-bottom: 22px;
        }

        .info-box {
            background: #eff6ff;
            color: #1e3a8a;
            padding: 14px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .balance {
            font-size: 30px;
            font-weight: bold;
            color: #2563eb;
            margin-top: 8px;
        }

        .success {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        label {
            display: block;
            font-weight: bold;
            margin-bottom: 6px;
            color: #374151;
        }

        input,
        textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 15px;
        }

        textarea {
            min-height: 90px;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .btn {
            padding: 11px 16px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
        }

        .btn-primary {
            background: #2563eb;
            color: white;
        }

        .btn-gray {
            background: #6b7280;
            color: white;
        }

        .actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 20px;
        }

        .hint {
            color: #6b7280;
            font-size: 13px;
            margin-top: 6px;
        }
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="card">

        <h1>Customer Transfer</h1>
        <p class="subtitle">Send credit to another customer wallet.</p>

        <div class="info-box">
            <strong>Your Customer Code:</strong>
            <?php echo htmlspecialchars($sender["customer_code"]); ?>

            <br><br>

            <strong>Your Balance</strong>
            <div class="balance">
                <?php echo number_format($sender["balance"], 2); ?>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label>Receiver Customer Code</label>
                <input
                    type="text"
                    name="receiver_code"
                    placeholder="CUS000007"
                    value="<?php echo htmlspecialchars($prefill_receiver_code); ?>"
                    required>
                <div class="hint">Enter customer code or scan customer QR code.</div>
            </div>

            <div class="form-group">
                <label>Amount</label>
                <input
                    type="text"
                    id="amount"
                    name="amount"
                    placeholder="10,000"
                    autocomplete="off"
                    required>
            </div>

            <div class="form-group">
                <label>Note</label>
                <textarea name="note" placeholder="Optional note"></textarea>
            </div>

            <div class="actions">
                <button class="btn btn-primary" type="submit">Transfer</button>
                <a class="btn btn-gray" href="dashboard.php">Back to Dashboard</a>
            </div>
        </form>

    </div>
</div>
<script>
const amountInput = document.getElementById('amount');

amountInput.addEventListener('input', function () {

    let value = this.value.replace(/,/g, '');
    value = value.replace(/[^\d]/g, '');

    if (value === '') {
        this.value = '';
        return;
    }

    this.value = Number(value).toLocaleString('en-US');
});

document.querySelector('form').addEventListener('submit', function () {
    amountInput.value = amountInput.value.replace(/,/g, '');
});
</script>
</body>
</html>