<?php
require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';
require_once '../includes/mailer.php';

/* ==========================
   ENABLE STRICT MYSQL ERRORS
========================== */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* ==========================
   GET USER
========================== */
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    die("User not found.");
}

$message = "";

/* ==========================
   UPDATE USER
========================== */
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];

    $address  = $_POST['address'];
    $city     = $_POST['city'];
    $state    = $_POST['state'];
    $zip_code = $_POST['zip_code'];
    $country  = $_POST['country'];

    $account_type = $_POST['account_type'];
    $currency     = $_POST['currency'];
    $status       = $_POST['status'];

    /* ==========================
       PROFILE PHOTO
    ========================== */
    $profile_photo = $user['profile_photo'];

    if (!empty($_FILES['profile_photo']['name'])) {

        $targetDir = "../uploads/profile_photos/";

        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }

        $fileName = time() . "_" . basename($_FILES["profile_photo"]["name"]);
        $targetFile = $targetDir . $fileName;

        move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $targetFile);

        $profile_photo = $fileName;
    }

    /* ==========================
       PASSWORD HANDLING
    ========================== */
    $password_set = false;
    $password_hash = null;

    if (!empty($_POST['password'])) {
        $password_set = true;
        $password_hash = password_hash($_POST['password'], PASSWORD_BCRYPT);
    }

    try {

        /* ==========================
           BUILD SAFE QUERY
        ========================== */
        $sql = "
            UPDATE users SET
                first_name = ?,
                last_name = ?,
                email = ?,
                phone = ?,
                address = ?,
                city = ?,
                state = ?,
                zip_code = ?,
                country = ?,
                account_type = ?,
                currency = ?,
                status = ?,
                profile_photo = ?
        ";

        $params = [
            $first_name,
            $last_name,
            $email,
            $phone,
            $address,
            $city,
            $state,
            $zip_code,
            $country,
            $account_type,
            $currency,
            $status,
            $profile_photo
        ];

        $types = str_repeat("s", count($params));

        /* PASSWORD OPTIONAL */
        if ($password_set) {
            $sql .= ", password = ?";
            $params[] = $password_hash;
            $types .= "s";
        }

        $sql .= " WHERE id = ?";
        $params[] = $id;
        $types .= "i";

        /* ==========================
           EXECUTE UPDATE
        ========================== */
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();

        /* ==========================
           EMAIL NOTIFICATION
        ========================== */
        $fullName = $first_name . " " . $last_name;

        sendMail(
            $email,
            "Account Updated",
            "Hello $fullName, your Texas Capital Bank account was updated by the bank admin."
        );

        header("Location: edit_user.php?id=$id&success=1");
        exit;

    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
    }
}

/* ==========================
   REFRESH USER DATA
========================== */
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

/* ==========================
   VIEW
========================== */
ob_start();
?>

<div class="main-content">

    <h2>Edit User</h2>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert success">User updated successfully!</div>
    <?php endif; ?>

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

    <form method="POST" enctype="multipart/form-data">

        <h3>Personal Info</h3>

        <input type="text" name="first_name" value="<?= htmlspecialchars($user['first_name']) ?>" required>
        <input type="text" name="last_name" value="<?= htmlspecialchars($user['last_name']) ?>" required>
        <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>
        <input type="text" name="phone" value="<?= htmlspecialchars($user['phone']) ?>">

        <h3>Address</h3>

        <input type="text" name="address" value="<?= htmlspecialchars($user['address']) ?>">
        <input type="text" name="city" value="<?= htmlspecialchars($user['city']) ?>">
        <input type="text" name="state" value="<?= htmlspecialchars($user['state']) ?>">
        <input type="text" name="zip_code" value="<?= htmlspecialchars($user['zip_code']) ?>">
        <input type="text" name="country" value="<?= htmlspecialchars($user['country']) ?>">

        <h3>Account Settings</h3>

        <select name="account_type">
            <option value="savings" <?= $user['account_type']=='savings'?'selected':'' ?>>Savings</option>
            <option value="current" <?= $user['account_type']=='current'?'selected':'' ?>>Current</option>
            <option value="business" <?= $user['account_type']=='business'?'selected':'' ?>>Business</option>
        </select>

        <select name="currency">
            <option value="USD" <?= $user['currency']=='USD'?'selected':'' ?>>USD</option>
            <option value="EUR" <?= $user['currency']=='EUR'?'selected':'' ?>>EUR</option>
            <option value="GBP" <?= $user['currency']=='GBP'?'selected':'' ?>>GBP</option>
            <option value="NGN" <?= $user['currency']=='NGN'?'selected':'' ?>>NGN</option>
        </select>

        <select name="status">
            <option value="active" <?= $user['status']=='active'?'selected':'' ?>>Active</option>
            <option value="suspended" <?= $user['status']=='suspended'?'selected':'' ?>>Suspended</option>
            <option value="deactivated" <?= $user['status']=='deactivated'?'selected':'' ?>>Deactivated</option>
        </select>

        <h3>Change Password</h3>
        <input type="password" name="password" placeholder="New Password">

        <h3>Profile Photo</h3>
        <input type="file" name="profile_photo">

        <br><br>
        <button type="submit">Update User</button>

    </form>

</div>

<?php
$content = ob_get_clean();
$page_title = "Edit User";
include '../components/admin_layout.php';
?>