<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ SET ZAMBIA TIMEZONE (LUSAKA)
date_default_timezone_set('Africa/Porto-Novo');

session_start();
include 'db.php'; // DB connection

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

// ✅ Pata balance kutoka users table
$stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user_data = $result->fetch_assoc();
$stmt->close();

$balance = isset($user_data['balance']) ? floatval($user_data['balance']) : 0.0;

// ✅ Block specific users
$blocked_users = [4, 5];
$message = "";
$redirect = "";

// Check if user is blocked
if (in_array($user_id, $blocked_users)) {
    $message = "❌ Your withdrawal privileges are temporarily disabled. Please contact your hiring manager.";
} else {

    // ✅ Pata user bank details
    $stmt = $conn->prepare("SELECT mpesa_name, mpesa_number, withdrawal_password FROM user_bank_details WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $bank = $res->fetch_assoc();
    $stmt->close();

    if (
        !$bank ||
        empty($bank['mpesa_name']) ||
        empty($bank['mpesa_number']) ||
        empty($bank['withdrawal_password'])
    ) {
        $message = "Please complete your bank details (Account Name, Number, and Fund Password) before withdrawing.";
        $redirect = "settings.php";
    }

    // Handle withdrawal request
    if (empty($message) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'], $_POST['fund_password'])) {

        $amount = floatval($_POST['amount']);
        $fund_pass = $_POST['fund_password'];

        // --- Restriction 0: Daily limit ---
        $stmt = $conn->prepare("
            SELECT COUNT(*) as cnt 
            FROM withdrawals 
            WHERE user_id = ? 
            AND DATE(created_at) = CURDATE()
        ");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();
        $stmt->close();

        if ($row && intval($row['cnt']) > 0) {
            $message = "You can only withdraw once per day. Please try again tomorrow.";
        }

        // --- Restriction 1: Time check (Mon–Fri, 10:00–17:00 Benin time) ---
        if (empty($message)) {
            try {
                $dt = new DateTime('now', new DateTimeZone('Africa/Porto-Novo'));
                $dayNum = (int)$dt->format('N'); // 1=Mon ... 7=Sun
                $hour   = (int)$dt->format('H');

                if ($dayNum < 1 || $dayNum > 5 || $hour < 10 || $hour >= 17) {
                    $message = "Withdrawals are allowed Monday to Friday between 10:00 and 17:00 Benin time.";
                }
            } catch (Exception $e) {
                $message = "Server timezone error. Try again later.";
            }
        }

        // --- Restriction 2: Must have active investment ---
        if (empty($message)) {
            $stmt = $conn->prepare("
                SELECT COUNT(*) as cnt 
                FROM investments 
                WHERE user_id = ? 
                AND status = 'active'
            ");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $res = $stmt->get_result();
            $row = $res->fetch_assoc();
            $stmt->close();

            if (!$row || intval($row['cnt']) === 0) {
                $message = "You must have an active investment to withdraw.";
            }
        }

        // --- Check fund password & balance ---
        if (empty($message)) {

            if (!password_verify($fund_pass, $bank['withdrawal_password'])) {
                $message = "Invalid fund password!";
            } elseif ($amount <= 0) {
                $message = "Invalid withdrawal amount.";
            } else {

                // Refresh balance
                $stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
                $stmt->bind_param("i", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();
                $user_data = $result->fetch_assoc();
                $stmt->close();

                $balance = isset($user_data['balance']) ? floatval($user_data['balance']) : 0.0;

                if ($balance < $amount) {
                    $message = "Insufficient balance!";
                } else {

                    // ✅ Process withdrawal
                    $conn->begin_transaction();
                    try {

                        // 1. Deduct amount
                        $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
                        $stmt->bind_param("di", $amount, $user_id);
                        $stmt->execute();
                        $stmt->close();

                        // 2. Net amount (10% fee)
                        $net_amount = $amount * 0.90;

                        // 3. Insert withdrawal record
                        $stmt = $conn->prepare("
                            INSERT INTO withdrawals 
                            (type, user_id, wallet, amount, status, created_at, updated_at) 
                            VALUES ('withdrawal', ?, 'main', ?, 'To be paid', NOW(), NOW())
                        ");
                        $stmt->bind_param("id", $user_id, $net_amount);
                        $stmt->execute();
                        $stmt->close();

                        $conn->commit();
                        $message = "Withdrawal request submitted successfully!";

                    } catch (Exception $e) {
                        $conn->rollback();
                        $message = "Error processing withdrawal. Please try again.";
                    }
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Withdrawal</title>
<style>
 body::before{
        content:"";
        position:fixed;top:0;left:0;width:100%;height:100%;
        background:url("bodyw.jpg") no-repeat center/cover;
        filter:blur(40px);transform:scale(1.1);z-index:-2
    }
body{font-family: Arial,sans-serif;}
header{display:flex;align-items:center;justify-content:space-between;padding:12px 15px;border-bottom:1px solid #ddd;background:#fff;}
header h1{font-size:18px;font-weight:500;margin:0;}
header a{font-size:15px;text-decoration:none;color:#4db3ff;font-weight:bold;}
.container{padding:15px;}
.balance-box{background:#fff;border-radius:10px;padding:15px;margin-bottom:15px;}
.balance-box div{display:flex;justify-content:space-between;padding:8px 0;font-size:16px;border-bottom:1px solid #eee;}
.balance-box div:last-child{border-bottom:none;}
.amount-box,.fund-pass{background:#fff;border-radius:10px;padding:15px;margin-bottom:15px;}
.amount-box label{display:block;margin-bottom:10px;font-weight:bold;}
.amount-btns{display:flex;flex-wrap:wrap;gap:10px;margin-top:10px;}
.amount-btns button{flex:1 1 30%;padding:12px 0;font-size:16px;border:1px solid #ddd;border-radius:6px;background:#fff;cursor:pointer;}
.amount-btns button.active{background: #08745a;  color:#fff;border:none;}
.submit-btn{width:100%;padding:15px;  background: #147238;border:none;color:#fff;font-size:18px;border-radius:6px;cursor:pointer;}
.notice{font-size:13px;color:#666;margin-bottom:10px;}
.popup-overlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9998;}
.popup{display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);  background:white;  padding:20px 25px;border-radius:10px;box-shadow:0 4px 15px rgba(0,0,0,0.2);text-align:center;z-index:9999;max-width:320px;}
.popup p{margin:0 0 15px;font-size:16px;}
.popup button{padding:8px 15px;border:none;background:transparent;color:red;border-radius:6px;cursor:pointer;font-size:14px;}
.notes{margin-top:20px;font-size:13px;color:#333;background:#fff;padding:10px;border-radius:10px;}
 *{-webkit-user-select:none;user-select:none}
 .usdt-btn{
    margin-top:20px;
    width:100%;
    padding:15px;
    border-radius:8px;
    background:linear-gradient(90deg,#26a17b,#1e8f6a);
    color:#fff;
    font-size:16px;
    font-weight:bold;
    border:none;
    cursor:pointer;
}
</style>
</head>
<body>
<header>
  <h1>Withdrawal</h1>
  <div class="wallet" onclick="window.location.href='records.php'">
 Withdraw Record
</div>
</header>
<div class="container">
  <div class="balance-box">
    <div><span>Available Balance:</span><span><?php echo number_format($balance,2); ?></span></div>
  </div>
  
  <form method="POST">
    <div class="amount-box">
      <div style="display:flex;justify-content:space-between;">
        <span>Withdrawal amount</span>
        <span>Fee: <span id="tax-amount">0</span></span>
      </div>
      <div class="amount-btns">
        <button type="button" data-amount="2000">2000</button>
        <button type="button" data-amount="7000">7000</button>
        <button type="button" data-amount="35000">35000</button>
        <button type="button" data-amount="100000">100000</button>
        <button type="button" data-amount="550000">550000</button>
        <button type="button" data-amount="2000000">2000000</button>
        <button type="button" data-amount="10000000">10000000</button>
        <button type="button" data-amount="70000000">70000000</button>
        <button type="button" data-amount="200000000">200000000</button>
      </div>
      <input type="hidden" name="amount" id="selected-amount">
    </div>
    <div class="fund-pass">
      <input type="password" name="fund_password" placeholder="Please input fund password">
    </div>
    <button class="submit-btn" type="submit">Submit</button>
  </form>

  <!-- Notes 📝 -->
  <div class="notes">
    <b>Notes 📝:</b>
    <ul>
        <li>Ensure your Account Name, Bank Account Number, and Fund Password are set in your bank details.</li>
        <li>Withdrawals are only allowed Monday to Friday between 10:00–17:00 Benin time.</li>
        <li>You can only withdraw <b>once per day</b>.</li>
    
        <li>10% fee is applied to all withdrawals automatically.</li>
    </ul>
  </div>
</div>

<div class="popup-overlay" id="popup-overlay"></div>
<div class="popup" id="popup">
  <p id="popup-message"></p>
  <button id="popup-ok">OK</button>
</div>
</div>
<!-- USDT WITHDRAW BUTTON -->
<div style="padding:15px;">
    <button 
        class="usdt-btn" 
        onclick="window.location.href='#'">
        Withdraw via USDT
    </button>
</div>
<div class="popup-overlay" id="popup-overlay"></div>
<script>
const buttons=document.querySelectorAll(".amount-btns button");
const taxAmount=document.getElementById("tax-amount");
const selectedAmountInput=document.getElementById("selected-amount");
buttons.forEach(btn=>{
  btn.addEventListener("click",()=>{
    buttons.forEach(b=>b.classList.remove("active"));
    btn.classList.add("active");
    const amount=parseFloat(btn.dataset.amount);
    const tax=amount*0.10;
    taxAmount.textContent=tax.toLocaleString();
    selectedAmountInput.value=amount;
  });
});
function showPopup(message,redirect){
  document.getElementById("popup-message").innerText=message;
  document.getElementById("popup-overlay").style.display="block";
  document.getElementById("popup").style.display="block";
  document.getElementById("popup-ok").onclick=function(){
    closePopup();
    if(redirect){window.location.href=redirect;}
  };
}
function closePopup(){
  document.getElementById("popup").style.display="none";
  document.getElementById("popup-overlay").style.display="none";
}
<?php if (!empty($message)): ?>
showPopup("<?php echo addslashes($message); ?>","<?php echo $redirect; ?>");
<?php endif; ?>
</script>

</body>
</html>