<?php
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');


/* ================= LOGIN CHECK ================= */

if (!isset($_SESSION['phone'])) {

    header("Location: login.php");
    exit;
}

$login_user = $_SESSION['phone'];

$successMsg = "";
$errorMsg   = "";

/* ================= ADMIN CHECK ================= */

$adminData = mysqli_fetch_assoc(
    mysqli_query(
        $ahk_conn,
        "SELECT * FROM users WHERE phone='$login_user' LIMIT 1"
    )
);

if (!$adminData || $adminData['type'] != 'admin') {

    die("
    <div style='
        height:100vh;
        display:flex;
        justify-content:center;
        align-items:center;
        background:#f1f5f9;
        font-family:Arial;
    '>

        <div style='
            background:#fff;
            padding:40px;
            border-radius:20px;
            text-align:center;
            box-shadow:0 10px 30px rgba(0,0,0,.1);
        '>

            <h2 style='color:red;'>Access Denied</h2>

            <p>You are not authorized to access this page.</p>

            <a href='dashboard.php'
               style='
                    display:inline-block;
                    margin-top:15px;
                    background:#2563eb;
                    color:#fff;
                    padding:12px 25px;
                    border-radius:10px;
                    text-decoration:none;
               '>
               Back Dashboard
            </a>

        </div>

    </div>
    ");
}

/* ================= GET USER ================= */

$username = mysqli_real_escape_string(
    $ahk_conn,
    $_GET['user'] ?? ''
);

if (empty($username)) {

    die("Invalid User");
}

/* ================= USER DETAILS ================= */

$user = mysqli_fetch_assoc(
    mysqli_query(
        $ahk_conn,
        "SELECT * FROM users WHERE phone='$username' LIMIT 1"
    )
);

if (!$user) {

    die("User Not Found");
}

$current_balance = (float)$user['balance'];

/* ================= SUBMIT ================= */

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

    $amount = (float)($_POST['amount'] ?? 0);

    $type   = trim($_POST['type'] ?? '');

    $reason = trim($_POST['reason'] ?? '');

    if ($amount <= 0) {

        $errorMsg = "Invalid Amount";

    } elseif (empty($type)) {

        $errorMsg = "Select Transaction Type";

    } elseif (empty($reason)) {

        $errorMsg = "Select Reason";

    } else {

        /* ================= CREDIT ================= */

        if ($type == "Credit") {

            $new_balance = $current_balance + $amount;
        }

        /* ================= DEBIT ================= */

        elseif ($type == "Debit") {

            if ($current_balance < $amount) {

                $errorMsg = "Insufficient User Balance";

            } else {

                $new_balance = $current_balance - $amount;
            }

        } else {

            $errorMsg = "Invalid Transaction Type";
        }

        /* ================= UPDATE ================= */

        if (empty($errorMsg)) {

            $update = mysqli_query(
                $ahk_conn,
                "UPDATE users
                 SET balance='$new_balance'
                 WHERE phone='$username'"
            );

            if ($update) {

                /* ================= WALLET HISTORY ================= */

                mysqli_query($ahk_conn, "

                    INSERT INTO wallethistory
                    (
                        userid,
                        amount,
                        balance,
                        purpose,
                        status,
                        type
                    )

                    VALUES
                    (
                        '$username',
                        '$amount',
                        '$new_balance',
                        '$reason',
                        '1',
                        '$type'
                    )

                ");

                $successMsg = "Balance Updated Successfully";

                $current_balance = $new_balance;

            } else {

                $errorMsg = "Database Error";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Balance Transfer</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"/>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{
    background:#eef4ff;
    font-family:'Segoe UI',sans-serif;
}

/* ================= HEADER ================= */

.top-header{
    background:linear-gradient(135deg,#2563eb,#1d4ed8);
    padding:25px;
    border-radius:22px;
    color:#fff;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(37,99,235,.25);
}

.top-title{
    font-size:30px;
    font-weight:800;
}

.top-sub{
    opacity:.9;
    margin-top:5px;
}

/* ================= BUTTON ================= */

.admin-btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:#fff;
    color:#2563eb;
    padding:12px 22px;
    border-radius:12px;
    text-decoration:none;
    font-weight:700;
    transition:.3s;
}

.admin-btn:hover{
    transform:translateY(-2px);
    color:#1d4ed8;
}

/* ================= CARD ================= */

.card-box{
    background:#fff;
    padding:30px;
    border-radius:25px;
    box-shadow:0 15px 40px rgba(0,0,0,.08);
    position:relative;
    overflow:hidden;
}

.card-box::before{
    content:'';
    position:absolute;
    width:180px;
    height:180px;
    background:rgba(37,99,235,.05);
    border-radius:50%;
    top:-70px;
    right:-70px;
}

/* ================= USER INFO ================= */

.user-info{
    background:linear-gradient(135deg,#eff6ff,#dbeafe);
    border:1px solid #bfdbfe;
    border-radius:18px;
    padding:20px;
    margin-bottom:25px;
}

.user-info h5{
    color:#1d4ed8;
    font-weight:700;
    margin-bottom:15px;
}

.info-item{
    margin-bottom:10px;
    font-size:15px;
}

.balance-box{
    background:#2563eb;
    color:#fff;
    padding:15px;
    border-radius:15px;
    text-align:center;
    margin-top:15px;
}

.balance-box h2{
    margin:0;
    font-size:32px;
    font-weight:800;
}

/* ================= FORM ================= */

.form-label{
    font-weight:700;
    color:#334155;
}

.form-control,
.form-select{
    height:52px;
    border-radius:14px;
    border:1px solid #dbe3f0;
    padding-left:15px;
}

.form-control:focus,
.form-select:focus{
    border-color:#2563eb;
    box-shadow:0 0 0 4px rgba(37,99,235,.12);
}

/* ================= SUBMIT ================= */

.submit-btn{
    background:linear-gradient(135deg,#2563eb,#1d4ed8);
    border:none;
    height:55px;
    border-radius:15px;
    color:#fff;
    font-size:17px;
    font-weight:700;
    transition:.3s;
}

.submit-btn:hover{
    transform:translateY(-2px);
    box-shadow:0 10px 25px rgba(37,99,235,.25);
}

/* ================= MOBILE ================= */

@media(max-width:768px){

    .top-title{
        font-size:24px;
    }

    .admin-btn{
        width:100%;
        justify-content:center;
    }

    .card-box{
        padding:22px;
    }
}

</style>

</head>

<body>

<div class="container py-4">

<!-- ================= HEADER ================= -->

<div class="top-header">

<div class="d-flex justify-content-between align-items-center flex-wrap gap-3">

<div>

<div class="top-title">

<i class="fa-solid fa-wallet me-2"></i>

Balance Transfer

</div>

<div class="top-sub">

Credit or debit user wallet balance instantly

</div>

</div>

<a href="admindash.php" class="admin-btn">

<i class="fa-solid fa-arrow-left"></i>

Back To Admin Panel

</a>

</div>

</div>

<!-- ================= FORM ================= -->

<div class="row justify-content-center">

<div class="col-lg-6">

<div class="card-box">

<!-- USER INFO -->

<div class="user-info">

<h5>

<i class="fa-solid fa-user me-2"></i>

User Details

</h5>

<div class="info-item">

<b>Name :</b>

<?= htmlspecialchars($user['name']) ?>

</div>

<div class="info-item">

<b>Phone :</b>

<?= htmlspecialchars($user['phone']) ?>

</div>

<div class="balance-box">

<div>Current Wallet Balance</div>

<h2>

₹<?= number_format($current_balance,2) ?>

</h2>

</div>

</div>

<!-- FORM -->

<form method="POST">

<div class="mb-3">

<label class="form-label">

Amount

</label>

<input type="number"
step="0.01"
name="amount"
class="form-control"
placeholder="Enter Amount"
required>

</div>

<div class="mb-3">

<label class="form-label">

Transaction Type

</label>

<select name="type"
class="form-select"
required>

<option value="">Select Type</option>

<option value="Credit">

Credit Balance

</option>

<option value="Debit">

Debit Balance

</option>

</select>

</div>

<div class="mb-4">

<label class="form-label">

Reason

</label>

<select name="reason"
class="form-select"
required>

<option value="">Select Reason</option>

<option value="Add Balance">Add Balance</option>

<option value="Refund">Refund</option>

<option value="Charge">Charge</option>

<option value="Bonus">Bonus</option>

<option value="Penalty">Penalty</option>

</select>

</div>

<button type="submit"
name="submit"
class="btn submit-btn w-100">

<i class="fa-solid fa-paper-plane me-2"></i>

Submit Transaction

</button>

</form>

</div>

</div>

</div>

</div>

<?php if($successMsg): ?>

<script>

Swal.fire({
    icon:'success',
    title:'Success',
    text:<?= json_encode($successMsg) ?>
});

</script>

<?php endif; ?>

<?php if($errorMsg): ?>

<script>

Swal.fire({
    icon:'error',
    title:'Failed',
    text:<?= json_encode($errorMsg) ?>
});

</script>

<?php endif; ?>

<?php include('footer.php'); ?>

</body>
</html>