<?php
// app/withdraw.php
header('Content-Type: application/json');
require_once '../config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

$user_id = $_SESSION['user_id'];
$amount  = (float)($_POST['amount']    ?? 0);
$method  = trim($_POST['method']       ?? '');
$holder  = trim($_POST['holder_name']  ?? '');

$network_or_bank   = '';
$mobile_or_account = '';

if ($method === 'Bank transfer') {
    $network_or_bank   = trim($_POST['bank'] ?? '');
    $mobile_or_account = trim($_POST['account_number'] ?? '');
} else {
    $network_or_bank   = trim($_POST['network'] ?? '');
    $mobile_or_account = trim($_POST['mobile_number'] ?? '');
}

$site_settings = get_site_settings($pdo);
$min_withdrawal = $site_settings['min_withdrawal'] ?? 1000;
$system_comm = $site_settings['system_commission'] ?? 0;
$allow_withdrawals = $site_settings['allow_withdrawals'] ?? 1;

// 1. Validation
if (!$allow_withdrawals) {
    echo json_encode(['success' => false, 'message' => 'Withdrawals are currently disabled for system maintenance.']);
    exit;
}

if ($amount < $min_withdrawal) {
    echo json_encode(['success' => false, 'message' => 'Minimum withdrawal is ' . number_format($min_withdrawal) . ' TZS.']);
    exit;
}

if (empty($method) || empty($network_or_bank) || empty($mobile_or_account) || empty($holder)) {
    echo json_encode(['success' => false, 'message' => 'Please fill in all recovery fields.']);
    exit;
}

try {
    // 2. Re-calculate Balance (Backend Truth) - Apply Commission
    $stmt = $pdo->prepare("SELECT SUM(amount) as gross_earned FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ? AND t.status = 'completed'");
    $stmt->execute([$user_id]);
    $gross_earned = $stmt->fetch()['gross_earned'] ?? 0;
    
    $total_earned = $gross_earned * (1 - ($system_comm / 100));

    $stmt = $pdo->prepare("SELECT SUM(amount) as withdrawn FROM withdrawals WHERE user_id = ? AND status IN ('completed', 'pending')");
    $stmt->execute([$user_id]);
    $total_withdrawn = $stmt->fetch()['withdrawn'] ?? 0;

    $available = $total_earned - $total_withdrawn;

    if ($amount > $available) {
        echo json_encode(['success' => false, 'message' => 'Insufficient balance. Available: TSH ' . number_format($available)]);
        exit;
    }

    // 3. Process Withdrawal
    $withdrawal_id = 'WDR-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -4));
    
    $stmt = $pdo->prepare("INSERT INTO withdrawals (withdrawal_id, user_id, amount, method, network_or_bank, mobile_or_account, account_holder_name, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')");
    $stmt->execute([$withdrawal_id, $user_id, $amount, $method, $network_or_bank, $mobile_or_account, $holder]);

    // 4. Notify Admin via NextSMS
    if (defined('NEXTSMS_ADMIN_PHONE')) {
        $user_name = $_SESSION['user_name'] ?? 'A user';
        $msg = "SonicPesa: New Withdrawal Request!\nUser: $user_name\nAmount: TSH " . number_format($amount) . "\nMethod: $method\nDest: $mobile_or_account";
        send_nextsms(NEXTSMS_ADMIN_PHONE, $msg);
    }

    echo json_encode(['success' => true, 'message' => 'Withdrawal request submitted successfully! Our team will process it shortly.']);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}

