<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once 'db.php';

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

$user_id = $_SESSION['user_id'];
$message = "";
$message_color = "#0f0";

// Get balance
$stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($balance);
$stmt->fetch();
$stmt->close();

// Handle withdrawal
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $amount = floatval($_POST['amount']);
  $phone = trim($_POST['phone']);
  $mpesa_name = trim($_POST['mpesa_name']);

  if ($amount <= 0 || empty($phone) || empty($mpesa_name)) {
    $message = "❌ Please fill all fields correctly.";
    $message_color = "red";
  } elseif ($amount < 50) {
    $message = "❌ Minimum withdrawal amount is ZMW 50.";
    $message_color = "red";
  } elseif ($amount > $balance) {
    $message = "❌ Insufficient balance!";
    $message_color = "red";
  } else {
    // Save withdrawal request
    $stmt = $conn->prepare("INSERT INTO withdrawals (user_id, amount, mpesa_number, mpesa_name, status) VALUES (?, ?, ?, ?, 'pending')");
    $stmt->bind_param("idss", $user_id, $amount, $phone, $mpesa_name);
    if ($stmt->execute()) {
      $stmt2 = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
      $stmt2->bind_param("di", $amount, $user_id);
      $stmt2->execute();
      $stmt2->close();

      $message = "✅ Withdrawal request submitted!";
    } else {
      $message = "❌ Failed to submit. Try again later.";
      $message_color = "red";
    }
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Withdraw</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
  <style>
    body {
      background: #0d1b2a;
      color: #fff;
      font-family: 'Segoe UI', sans-serif;
      padding: 20px;
    }
    .withdraw-box {
      background: #1b263b;
      border-radius: 15px;
      padding: 20px;
      max-width: 450px;
      margin: auto;
      box-shadow: 0 0 15px rgba(0,150,255,0.4);
    }
    .withdraw-box h2 {
      color: #4dafff;
      margin-bottom: 20px;
      text-align: center;
    }
    .balance-box {
      background: #0f2d4a;
      padding: 15px;
      border-radius: 10px;
      margin-bottom: 20px;
      font-size: 16px;
      color: #a9c8ff;
    }
    .balance-box strong {
      color: #4dafff;
    }
    .input-group {
      margin-bottom: 15px;
    }
    .input-group label {
      display: block;
      margin-bottom: 5px;
      color: #b0c7e4;
    }
    .input-group input {
      width: 93%;
      padding: 10px;
      border: none;
      border-radius: 8px;
      background: #112f4c;
      color: #fff;
      outline: none;
    }
    .input-group input:focus {
      border: 1px solid #4dafff;
    }
    .submit-btn {
      width: 100%;
      padding: 12px;
      background: linear-gradient(to left, #4dafff, #00d4ff);
      color: #000;
      border: none;
      border-radius: 20px;
      font-weight: bold;
      cursor: pointer;
      margin-top: 10px;
    }
    .submit-btn:hover {
      opacity: 0.9;
    }
    .steps {
      font-size: 14px;
      background: #0f2d4a;
      padding: 10px;
      border-radius: 10px;
      margin-top: 20px;
      color: #c2d9f0;
    }
    .steps li {
      margin-bottom: 8px;
    }
    .msg {
      margin-bottom: 20px;
      background: #0f2d4a;
      border-left: 5px solid <?= $message_color ?>;
      padding: 10px 15px;
      border-radius: 10px;
      color: <?= $message_color ?>;
      font-weight: 500;
      animation: fadein 0.5s ease-in-out;
    }
    @keyframes fadein {
      from {opacity: 0;}
      to {opacity: 1;}
    }
  </style>
</head>
<body>

  <div class="withdraw-box">
    <h2>Withdraw to MTN/Airtel</h2>

    <?php if (!empty($message)): ?>
      <div class="msg"><?= $message ?></div>
    <?php endif; ?>

    <div class="balance-box">
      💰 Current Balance: <strong>ZMW <?= number_format($balance, 2) ?></strong>
    </div>

    <form method="post">
      <div class="input-group">
        <label for="amount">Amount (ZMW)</label>
        <input type="number" name="amount" id="amount" required />
      </div>

      <div class="input-group">
        <label for="phone">MTN/Airtel Phone Number</label>
        <input type="text" name="phone" id="phone" placeholder="e.g. 0XXXXXXXX" required />
      </div>

      <div class="input-group">
        <label for="mpesa_name">MTN/Airtel Name</label>
        <input type="text" name="mpesa_name" id="mpesa_name" placeholder="e.g. Mark Ogeyo" required />
      </div>

      <button type="submit" class="submit-btn">Submit Withdrawal</button>
    </form>

    <ul class="steps">
      <li>✅ Minimum withdrawal ZMW 50</li>
      <li>✅ Withdrawal tax 10%</li>
      <li>✅ You’ll receive funds via MTN/Airtel after approval</li>
      <li>✅ Make sure the name matches your MTN/Airtel account</li>
    </ul>
  </div>

</body>
</html>
