<?php
$pageName  = "Pincode";
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/header.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/include/Transfer/DomesticFunction.php");

if (!$_SESSION['is_dom_transfer']) {
    header("Location:./dashboard.php");
}

// TEMP TRANSACTION FETCH
$sql = "SELECT * FROM temp_trans WHERE user_id =:user_id ORDER BY trans_id DESC LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->execute(['user_id' => $user_id]);
$temp_trans = $stmt->fetch(PDO::FETCH_ASSOC);

if (isset($_POST['dom_submit'])) {

    $pin            = inputValidation($_POST['pin']);
    $oldPin         = inputValidation($row['acct_otp']);
    $acct_amount    = inputValidation($row['acct_balance']);
    $user_id        = inputValidation($_POST['user_id']);
    $amount         = inputValidation($_POST['amount']);
    $bank_name      = inputValidation($_POST['bank_name']);
    $account_name   = inputValidation($_POST['account_name']);
    $account_number = inputValidation($_POST['account_number']);
    $account_type   = inputValidation($_POST['account_type']);
    $bank_country   = inputValidation($_POST['bank_country']);

    $transferLimit = $row['limit_remain'];
    $amountfee     = $page['domesticfee'];

    if ($pin !== $oldPin) {
        toast_alert('error', 'Incorrect OTP Code');
    } elseif ($acct_amount < 0) {
        toast_alert('error', 'Insufficient Balance');
    } else {

        $tBalance   = ($transferLimit - $amount);
        $aBalance   = ($acct_amount - $amount);
        $feeBalance = ($aBalance - $amountfee);

        $sql = "UPDATE users SET limit_remain=:limit_remain, acct_balance=:acct_balance WHERE id=:id";
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            'limit_remain' => $tBalance,
            'acct_balance' => $feeBalance,
            'id'           => $user_id
        ]);

        $refrence_id      = uniqid();
        $trans_type       = "Domestic transfer";
        $transaction_type = "debit";
        $trans_status     = "processing";

        date_default_timezone_set('Europe/London');
        $created_at = date('Y-m-d H:i:s');

        $sql = "INSERT INTO transactions 
                    (amount, refrence_id, user_id, bank_name, account_name, account_number, account_type, bank_country, trans_type, transaction_type, trans_status, created_at) 
                VALUES 
                    (:amount, :refrence_id, :user_id, :bank_name, :account_name, :account_number, :account_type, :bank_country, :trans_type, :transaction_type, :trans_status, :created_at)";
        $tranfered = $conn->prepare($sql);
        $tranfered->execute([
            'amount'           => $amount,
            'refrence_id'      => $refrence_id,
            'user_id'          => $user_id,
            'bank_name'        => $bank_name,
            'account_name'     => $account_name,
            'account_number'   => $account_number,
            'account_type'     => $account_type,
            'bank_country'     => $bank_country,
            'trans_type'       => $trans_type,
            'transaction_type' => $transaction_type,
            'trans_status'     => $trans_status,
            'created_at'       => $created_at
        ]);

        $lastId = $conn->lastInsertId();
        $conn->prepare("UPDATE transactions SET created_at = :val WHERE trans_id = :tid")
             ->execute(['val' => $created_at, 'tid' => $lastId]);

        $full_name    = $row['firstname'] . " " . $row['lastname'];
        $APP_NAME     = WEB_TITLE;
        $APP_URL      = WEB_URL;
        $SITE_ADDRESS = $page['url_address'];
        $user_email   = $row['acct_email'];

        $message = $sendMail->DomMsg(
            $full_name, $amount, $account_number, $account_name,
            $account_type, $bank_country, $trans_type, $refrence_id,
            $trans_status, $APP_NAME, $APP_URL, $SITE_ADDRESS
        );
        $subject = "Domestic Transfer - $APP_NAME";
        $email_message->send_mail($user_email, $message, $subject);

        $_SESSION['dom_transfer'] = $refrence_id;
        $_SESSION['is_transfer']  = "transfer";
        header("Location:./success.php");
        exit;
    }
}
?>

<!-- Keyframes only — no Tailwind equivalent for these specific animations -->
<style>
    @keyframes progress {
        from { width: 100%; }
        to   { width: 0%; }
    }
</style>

<!-- Main Content -->
<main class="pt-10 md:pt-14 pb-24 md:pb-8 min-h-screen lg:ml-80 bg-slate-50">
<div class="min-h-screen flex items-center justify-center p-4 relative z-10">

<div class="w-full max-w-md mx-auto"
     x-cloak
     x-data="{
         otp: '',
         timer: 30,
         canResend: false,
         startTimer() {
             const interval = setInterval(() => {
                 if (this.timer > 0) {
                     this.timer--;
                 } else {
                     this.canResend = true;
                     clearInterval(interval);
                 }
             }, 1000);
         }
     }"
     x-init="startTimer()">

    <!-- OTP Verification Card -->
    <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-8 md:p-10 space-y-8">

        <!-- Header -->
        <div class="text-center space-y-4">
            <div class="relative inline-block">
                <div class="w-16 h-16 rounded-xl bg-primary-50 border border-primary-200 flex items-center justify-center mx-auto">
                    <i data-lucide="shield-check" class="w-8 h-8 text-primary-500"></i>
                </div>
            </div>
            <div>
                <h2 class="text-xl font-semibold text-slate-900">Verify Your Identity</h2>
                <p class="text-sm text-slate-500 mt-1">
                    We've sent a verification code to<br>
                    <span class="text-primary-600 font-semibold"><?= htmlspecialchars($row['acct_email']) ?></span>
                </p>
            </div>
        </div>

        <!-- Success Alert -->
        <div x-data="{ show: true }"
             x-show="show"
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0 translate-y-2"
             x-transition:enter-end="opacity-100 translate-y-0"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0">
            <div class="border border-green-200 rounded-xl overflow-hidden transition-all hover:-translate-y-0.5 hover:shadow-md">
                <div class="flex items-start p-4 gap-4">
                    <div class="flex-shrink-0">
                        <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-green-500 to-green-700 flex items-center justify-center shadow-lg relative">
                            <div class="absolute inset-0 bg-green-500/20 rounded-xl animate-pulse"></div>
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-white relative z-10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M20 6 9 17l-5-5"/>
                            </svg>
                        </div>
                    </div>
                    <div class="flex-1 min-w-0">
                        <h4 class="text-sm font-bold text-slate-900 mb-1">Code Sent!</h4>
                        <p class="text-sm text-slate-600 leading-relaxed">Verification code sent successfully. Please check your email.</p>
                    </div>
                    <button @click="show = false" class="flex-shrink-0 p-1.5 rounded-lg hover:bg-green-50 transition-colors">
                        <i data-lucide="x" class="w-4 h-4 text-slate-500"></i>
                    </button>
                </div>
                <div class="h-1 bg-green-100">
                    <div class="h-full bg-gradient-to-r from-green-500 to-green-400"
                         style="animation: progress 5s linear forwards;"
                         @animationend="show = false"></div>
                </div>
            </div>
        </div>

        <!-- OTP Form -->
        <form method="POST" class="space-y-6">

            <!-- Hidden transaction fields from temp_trans -->
            <input type="hidden" name="dom_submit"      value="1">
            <input type="hidden" name="user_id"         value="<?= $temp_trans['user_id'] ?>">
            <input type="hidden" name="amount"          value="<?= $temp_trans['amount'] ?>">
            <input type="hidden" name="bank_name"       value="<?= htmlspecialchars($temp_trans['bank_name']) ?>">
            <input type="hidden" name="account_name"    value="<?= htmlspecialchars($temp_trans['account_name']) ?>">
            <input type="hidden" name="account_number"  value="<?= $temp_trans['account_number'] ?>">
            <input type="hidden" name="account_type"    value="<?= htmlspecialchars($temp_trans['account_type']) ?>">
            <input type="hidden" name="bank_country"    value="<?= htmlspecialchars($temp_trans['bank_country']) ?>">
            <input type="hidden" name="trans_type"      value="<?= htmlspecialchars($temp_trans['trans_type']) ?>">

            <!-- OTP Input -->
            <div class="space-y-2">
                <label class="block text-sm font-semibold text-slate-700 text-center">
                    Enter Verification Code
                </label>
                <input
                    type="text"
                    name="pin"
                    x-model="otp"
                    @input="otp = otp.replace(/\D/g, '').slice(0, 6)"
                    maxlength="6"
                    inputmode="numeric"
                    pattern="[0-9]*"
                    placeholder="000000"
                    autocomplete="one-time-code"
                    autofocus
                    required
                    class="w-full text-center text-2xl font-bold tracking-[0.4em] rounded-xl py-4 px-4 bg-white border border-slate-200 text-slate-900 outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-100 transition-all">
            </div>

            <!-- Timer & Resend -->
            <div class="text-center">
                <div x-show="!canResend" class="text-sm text-slate-500">
                    Didn't receive the code? Resend in
                    <span class="font-bold text-primary-600" x-text="timer + 's'"></span>
                </div>
                <div x-show="canResend" class="text-sm">
                    <span class="text-slate-500">Didn't receive the code? </span>
                    <a href="./getotp.php" class="text-primary-600 hover:text-primary-700 font-semibold inline-flex items-center space-x-1 hover:underline">
                        <i data-lucide="refresh-cw" class="w-3 h-3"></i>
                        <span>Resend Code</span>
                    </a>
                </div>
            </div>

            <!-- Info Banner -->
            <div class="bg-primary-50 border border-primary-200 rounded-xl p-4">
                <div class="flex items-start space-x-3">
                    <i data-lucide="info" class="w-5 h-5 text-primary-500 flex-shrink-0 mt-0.5"></i>
                    <p class="text-xs text-slate-600">
                        This code will expire in 10 minutes. For your security, never share this code with anyone.
                    </p>
                </div>
            </div>

            <!-- Submit Button -->
            <button
                type="submit"
                :disabled="otp.length < 4"
                class="w-full py-4 rounded-xl font-semibold text-white text-sm flex items-center justify-center space-x-2 bg-primary-500 hover:bg-primary-600 shadow-sm hover:shadow-md transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:shadow-sm group">
                <i data-lucide="check-circle" class="w-5 h-5"></i>
                <span>Verify & Complete Transfer</span>
                <i data-lucide="arrow-right" class="w-5 h-5 group-hover:translate-x-1 transition-transform"></i>
            </button>

            <p class="text-xs text-center text-slate-500">
                <i data-lucide="lock" class="w-3 h-3 inline mr-1"></i>
                Your security is protected with end-to-end encryption
            </p>
        </form>

        <!-- Footer -->
        <div class="pt-6 border-t border-slate-200">
            <div class="flex items-center justify-between text-xs text-slate-500">
                <a href="./dashboard.php" class="text-primary-600 hover:text-primary-700 inline-flex items-center space-x-1 group hover:underline">
                    <i data-lucide="arrow-left" class="w-4 h-4 group-hover:-translate-x-1 transition-transform"></i>
                    <span>Back to Dashboard</span>
                </a>
                <span>Secure Connection</span>
            </div>
        </div>

    </div>
</div>
</div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function () {
    lucide.createIcons();
});
</script>

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/footer.php");
?>