<?php
// admin/user_edit.php

// --- 1. Debugging Enable ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
// Check config path
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} else {
    require_once "../includes/config.php";
}

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

// --- 3. Validate User ID ---
$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    die("<div style='color:red;padding:20px;text-align:center;'>❌ Invalid User ID. <a href='users.php'>Go Back</a></div>");
}

// --- 4. Handle DELETE BANK Action ---
if (isset($_POST['delete_bank'])) {
    $stmt = $conn->prepare("UPDATE users SET bank_name=NULL, account_holder=NULL, account_number=NULL, ifsc=NULL WHERE id=?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $success = "✅ Bank details deleted successfully!";
    } else {
        $error = "❌ Failed to delete bank details.";
    }
    $stmt->close();
}

// --- 5. Handle Form Submission (Update) ---
$success = $error = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['delete_bank'])) {
    
    // 1. Get Wallet Values
    $income_balance  = (float)$_POST['income_balance'];
    $deposit_balance = (float)$_POST['deposit_balance'];
    $bonus_balance   = (float)$_POST['bonus_balance'];
    
    // 2. Calculate Total Main Balance (Column 3 in your schema)
    // Isse ye ensure hoga ki Total Balance hamesha teeno ka jod ho.
    $total_balance = $income_balance + $deposit_balance + $bonus_balance;
    
    // 3. Get Bank Details
    $bank_name       = trim($_POST['bank_name']);
    $account_holder  = trim($_POST['account_holder']);
    $account_number  = trim($_POST['account_number']);
    $ifsc            = trim($_POST['ifsc']);
    
    // 4. Get Passwords
    $withdraw_password = $_POST['withdraw_password'];
    $login_password    = $_POST['login_password'];

    // --- Build Query ---
    // Note: Updated 'balance' column along with specific balances
    $query = "UPDATE users SET income_balance=?, deposit_balance=?, bonus_balance=?, balance=?, bank_name=?, account_holder=?, account_number=?, ifsc=?";
    $types = "ddddssss"; // 4 decimals, 4 strings
    $params = [$income_balance, $deposit_balance, $bonus_balance, $total_balance, $bank_name, $account_holder, $account_number, $ifsc];

    // Only update passwords if they are NOT empty
    if (!empty($withdraw_password)) {
        $query .= ", withdraw_password=?";
        $types .= "s";
        $params[] = $withdraw_password; // Storing as plain text based on typical source codes (Change to hash if needed)
    }

    if (!empty($login_password)) {
        // FIX: Schema name is 'login_password', not 'password'
        $query .= ", login_password=?"; 
        $types .= "s";
        // Using Bcrypt hash for login password
        $params[] = password_hash($login_password, PASSWORD_BCRYPT);
    }

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

    // Execute Update
    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param($types, ...$params);
        if ($stmt->execute()) {
            $success = "✅ User details updated successfully!";
            // Redirect to avoid resubmission
            header("Location: user_edit.php?id=$id&success=" . urlencode($success));
            exit();
        } else {
            $error = "❌ Update failed: " . $stmt->error;
        }
        $stmt->close();
    } else {
        $error = "❌ Query Prep failed: " . $conn->error;
    }
}

// --- 6. Fetch User Data ---
$stmt = $conn->prepare("SELECT id, mobile, income_balance, deposit_balance, bonus_balance, bank_name, account_holder, account_number, ifsc FROM users WHERE id=? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$res = $stmt->get_result();
$user = $res->fetch_assoc();
$stmt->close();

if (!$user) {
    die("<div style='color:red;padding:20px;'>❌ User not found.</div>");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Edit User - #<?=$id?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

  <style>
    body {font-family:'Segoe UI',Arial,sans-serif; margin:0; background:#f4f6fb; color:#333;}

    /* Header */
    .header {
      display:flex; justify-content:space-between; align-items:center;
      background:linear-gradient(90deg,#0047ab,#2196f3);
      color:#fff; padding:14px 20px;
      box-shadow:0 4px 14px rgba(0,0,0,0.3);
      position:sticky; top:0; z-index:999;
    }
    .header h2 {margin:0; font-size:18px; letter-spacing:1px;}
    .back-btn {
      background:rgba(255,255,255,0.2); color:#fff; text-decoration:none;
      padding:8px 14px; border-radius:6px; font-weight:bold; transition:0.3s;
      border:1px solid rgba(255,255,255,0.3);
    }
    .back-btn:hover {background:rgba(255,255,255,0.4);}

    /* Container */
    .container {
        max-width:700px; margin:30px auto; padding:30px; 
        background:#fff; border-radius:14px; 
        box-shadow:0 6px 18px rgba(0,0,0,0.1);
    }

    h3 {color:#0047ab; margin-top:0; border-bottom:2px solid #f0f0f0; padding-bottom:10px; margin-bottom:20px;}

    .form-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
    }

    .form-group {margin-bottom:15px;}
    .form-group.full { grid-column: 1 / -1; }

    label {font-weight:600; display:block; margin-bottom:6px; color:#555; font-size:14px;}
    input {
        width:100%; padding:12px; border:1px solid #ddd; border-radius:8px;
        font-size:15px; box-sizing:border-box; transition:0.3s;
    }
    input:focus {border-color:#2196f3; outline:none; box-shadow:0 0 6px rgba(33,150,243,0.3);}
    input[readonly] {background:#f8f9fa; color:#777; cursor:not-allowed;}

    /* Buttons */
    .btn-submit {
        background:linear-gradient(90deg,#0047ab,#2196f3);
        color:#fff; padding:15px; width:100%; border:none; border-radius:10px;
        font-size:16px; font-weight:bold; cursor:pointer; transition:0.3s;
        margin-top: 20px;
        box-shadow: 0 4px 12px rgba(0,71,171,0.3);
    }
    .btn-submit:hover {transform:translateY(-2px); box-shadow: 0 6px 15px rgba(0,71,171,0.4);}

    .btn-delete {
        background:#e74c3c; color:#fff; padding:10px 15px; border:none; 
        border-radius:8px; font-weight:bold; cursor:pointer; width:100%; margin-top:10px;
    }
    .btn-delete:hover {background:#c0392b;}

    /* Alerts */
    .alert {padding:15px; border-radius:8px; margin-bottom:20px; text-align:center; font-weight:bold;}
    .success {background:#d4edda; color:#155724; border:1px solid #c3e6cb;}
    .error {background:#f8d7da; color:#721c24; border:1px solid #f5c6cb;}

    /* History Links */
    .actions {display:flex; flex-wrap:wrap; gap:10px; margin-top:30px; border-top:1px solid #eee; padding-top:20px;}
    .action-btn {
        flex:1; text-align:center; text-decoration:none; padding:12px; border-radius:8px;
        color:#fff; font-weight:bold; font-size:14px; transition:0.3s; min-width: 140px;
    }
    .btn-hist {background:#607d8b;}
    .btn-dep {background:#009688;}
    .action-btn:hover {opacity:0.9; transform:translateY(-1px);}

    @media (max-width: 600px) {
        .form-grid { grid-template-columns: 1fr; }
        .container { margin: 15px; padding: 20px; }
    }
  </style>
</head>

<body>

  <div class="header">
    <a href="users.php" class="back-btn"><i class="fa-solid fa-arrow-left"></i> Back</a>
    <h2><i class="fa-solid fa-user-pen"></i> Edit User</h2>
  </div>

  <div class="container">
    
    <?php if(isset($_GET['success'])): ?>
        <div class="alert success"><?=htmlspecialchars($_GET['success'])?></div>
    <?php endif; ?>
    <?php if($error): ?>
        <div class="alert error"><?=$error?></div>
    <?php endif; ?>

    <form method="post">
      
      <h3>👤 Account Info</h3>
      <div class="form-grid">
          <div class="form-group">
            <label>User ID</label>
            <input type="text" value="<?=$user['id']?>" readonly>
          </div>
          <div class="form-group">
            <label>Mobile Number</label>
            <input type="text" value="<?=htmlspecialchars($user['mobile'])?>" readonly>
          </div>
      </div>

      <h3>💰 Balance Management</h3>
      <div class="form-grid">
          <div class="form-group">
            <label>Income Balance (₹)</label>
            <input type="number" step="0.01" name="income_balance" value="<?=$user['income_balance']?>" required>
          </div>
          <div class="form-group">
            <label>Bonus Balance (₹)</label>
            <input type="number" step="0.01" name="bonus_balance" value="<?=$user['bonus_balance']?>" required>
          </div>
          <div class="form-group">
            <label>Deposit Balance (₹)</label>
            <input type="number" step="0.01" name="deposit_balance" value="<?=$user['deposit_balance']?>" required>
          </div>
          <div class="form-group">
             <label>Total Calculated Balance: 
                 <span style="color:#0047ab;font-weight:bold;">₹<?=number_format($user['income_balance'] + $user['bonus_balance'] + $user['deposit_balance'], 2)?></span>
             </label>
             <small style="color:#666; display:block; margin-top:2px;">(Main Balance will auto-update to this sum)</small>
          </div>
      </div>

      <h3>🔒 Security</h3>
      <div class="form-grid">
          <div class="form-group">
            <label>New Withdraw Password</label>
            <input type="text" name="withdraw_password" placeholder="Leave empty to keep current">
          </div>
          <div class="form-group">
            <label>New Login Password</label>
            <input type="text" name="login_password" placeholder="Leave empty to keep current">
          </div>
      </div>

      <h3>🏦 Bank Details</h3>
      <div class="form-grid">
          <div class="form-group">
            <label>Bank Name</label>
            <input type="text" name="bank_name" value="<?=htmlspecialchars($user['bank_name'] ?? '')?>">
          </div>
          <div class="form-group">
            <label>Account Holder Name</label>
            <input type="text" name="account_holder" value="<?=htmlspecialchars($user['account_holder'] ?? '')?>">
          </div>
          <div class="form-group">
            <label>Account Number</label>
            <input type="text" name="account_number" value="<?=htmlspecialchars($user['account_number'] ?? '')?>">
          </div>
          <div class="form-group">
            <label>IFSC Code</label>
            <input type="text" name="ifsc" value="<?=htmlspecialchars($user['ifsc'] ?? '')?>">
          </div>
      </div>
      
      <button type="submit" name="delete_bank" value="1" class="btn-delete" onclick="return confirm('Are you sure you want to delete bank details for this user?');">
          <i class="fa-solid fa-trash"></i> Delete Bank Details
      </button>

      <button type="submit" class="btn-submit"><i class="fa-solid fa-floppy-disk"></i> Save Changes</button>
    </form>

    <div class="actions">
      <a href="withdraw.php?user_id=<?=$user['id']?>" class="action-btn btn-hist"><i class="fa-solid fa-clock-rotate-left"></i> Withdraw History</a>
      <a href="deposits.php?user_id=<?=$user['id']?>" class="action-btn btn-dep"><i class="fa-solid fa-wallet"></i> Deposit History</a>
    </div>

  </div>

</body>
</html>