<?php
session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin-login.php");
    exit;
}

require 'db/db.php';

if (!isset($_GET['uid']) || !is_numeric($_GET['uid'])) {
    die("<div class='alert alert-danger text-center p-5'>No valid user selected</div>");
}

$uid = (int)$_GET['uid'];

// Fetch user
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $uid);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows !== 1) {
    die("<div class='alert alert-danger text-center p-5'>User not found</div>");
}

$user = $result->fetch_assoc();
$stmt->close();

// ────────────────────────────────────────────────
// HANDLE FORM SUBMIT
$message = '';
$message_type = ''; // success / danger

if (isset($_POST['update_user'])) {
    $full_name       = trim($_POST['full_name'] ?? '');
    $account_number  = trim($_POST['account_number'] ?? '');
    $account_balance = floatval($_POST['account_balance'] ?? 0);
    $kyc_status      = $_POST['kyc_status'] ?? '';

    if (empty($full_name) || empty($account_number) || !in_array($kyc_status, ['Pending','Verified','Rejected'])) {
        $message = "Please fill all required fields correctly.";
        $message_type = 'danger';
    } else {
        $check = $conn->prepare("SELECT id FROM users WHERE account_number = ? AND id != ? LIMIT 1");
        $check->bind_param("si", $account_number, $uid);
        $check->execute();
        $check_result = $check->get_result();

        if ($check_result->num_rows > 0) {
            $message = "This account number is already in use by another user.";
            $message_type = 'danger';
        } else {
            $update = $conn->prepare("
                UPDATE users 
                SET full_name = ?, 
                    account_number = ?, 
                    account_balance = ?, 
                    kyc_status = ? 
                WHERE id = ?
            ");
            $update->bind_param("ssdsi", $full_name, $account_number, $account_balance, $kyc_status, $uid);

            if ($update->execute()) {
                $message = "User updated successfully!";
                $message_type = 'success';

                // Refresh user data
                $stmt = $conn->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
                $stmt->bind_param("i", $uid);
                $stmt->execute();
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();
            } else {
                $message = "Update failed: " . $update->error;
                $message_type = 'danger';
            }
            $update->close();
        }
        $check->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User</title>

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

    <link rel="stylesheet" href="assets/admin-edit-user.css">
</head>
<body>

<div class="app">

    <!-- TOP HEADER -->
    <div class="top-header">
        <a href="admin_view_user.php?uid=<?= $uid ?>" class="back-icon">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div>
            <small>Admin Panel</small>
            <h4>Edit User</h4>
        </div>
        <i class="bi bi-pencil"></i>
    </div>

    <!-- MESSAGE -->
    <?php if ($message): ?>
    <div class="container mt-4">
        <div class="alert alert-<?= $message_type ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>
    <?php endif; ?>

    <!-- FORM CARD -->
    <div class="card form-card">
        <form method="POST">
            <div class="form-group">
                <label>Full Name</label>
                <input type="text" name="full_name" 
                       value="<?= htmlspecialchars($user['full_name'] ?? '') ?>" 
                       required>
            </div>

            <div class="form-group">
                <label>Account Number</label>
                <input type="text" name="account_number" 
                       value="<?= htmlspecialchars($user['account_number'] ?? '') ?>" 
                       required>
            </div>

            <div class="form-group">
                <label>Account Balance (AED)</label>
                <input type="number" name="account_balance" step="0.01" 
                       value="<?= htmlspecialchars($user['account_balance'] ?? '0.00') ?>" 
                       required>
            </div>

            <div class="form-group">
                <label>KYC Status</label>
                <select name="kyc_status" required>
                    <option value="Pending"   <?= ($user['kyc_status'] ?? '') === 'Pending'   ? 'selected' : '' ?>>Pending</option>
                    <option value="Verified"  <?= ($user['kyc_status'] ?? '') === 'Verified'  ? 'selected' : '' ?>>Verified</option>
                    <option value="Rejected"  <?= ($user['kyc_status'] ?? '') === 'Rejected'  ? 'selected' : '' ?>>Rejected</option>
                </select>
            </div>

            <button type="submit" name="update_user" class="btn-save">
                <i class="bi bi-check-circle"></i> Save Changes
            </button>
        </form>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>