<?php
// FILE: public_html/Nag/credit_user.php
session_start();
include '../db.php';
// ✅ INCLUDE THE FCM HELPER (Ensure this file exists in /api folder)
// If you don't have it, I can provide the code for it.
require_once '../api/fcm_helper.php'; 

// 1. SECURITY: Check Admin Login (Matches Dashboard Logic)
if (!isset($_SESSION['admin_id'])) { 
    header("Location: index.php"); 
    exit(); 
}

$message = "";
$msg_type = ""; // success or error
$user_id = $_GET['id'] ?? '';
$user_data = null;

// Fetch user details to display name
if ($user_id) {
    $stmt = $conn->prepare("SELECT username, first_name, email FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $user_data = $stmt->get_result()->fetch_assoc();
}

// --- PROCESS FUNDING ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $uid = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']); 
    $type = $_POST['type']; 
    $reason = $_POST['reason'];
    $reference = "ADM" . time() . rand(100,999);

    if ($amount <= 0) {
        $message = "Error: Amount must be greater than 0.";
        $msg_type = "error";
    } else {
        // 1. Check if wallet exists
        $check = $conn->query("SELECT id FROM wallets WHERE user_id = $uid");
        
        if ($check->num_rows == 0) {
            // Wallet missing? Create it!
            $init_stmt = $conn->prepare("INSERT INTO wallets (user_id, balance) VALUES (?, 0.00)");
            $init_stmt->bind_param("i", $uid);
            $init_stmt->execute();
        }

        // 2. Perform Credit or Debit
        if ($type == 'credit') {
            // Update Balance (Add)
            $stmt = $conn->prepare("UPDATE wallets SET balance = balance + ? WHERE user_id = ?");
            $stmt->bind_param("di", $amount, $uid);
            
            if ($stmt->execute()) {
                // Log Transaction
                $log = $conn->prepare("INSERT INTO transactions (user_id, trans_ref, reference, amount, status, transaction_type, description, payment_source, created_at) VALUES (?, ?, ?, ?, 'success', 'credit', ?, 'admin', NOW())");
                $log->bind_param("issds", $uid, $reference, $reference, $amount, $reason);
                $log->execute();

                $notif_title = "Wallet Funded: ₦" . number_format($amount);
                $notif_body = "Your wallet has been credited with ₦" . number_format($amount) . ". Reason: $reason";

                // ✅ 3. SAVE NOTIFICATION TO DATABASE (So it shows in App History)
                $save_notif = $conn->prepare("INSERT INTO user_notifications (user_id, title, message, created_at, is_read) VALUES (?, ?, ?, NOW(), 0)");
                $save_notif->bind_param("iss", $uid, $notif_title, $notif_body);
                $save_notif->execute();

                // ✅ 4. SEND PUSH NOTIFICATION
                sendPushNotification($uid, $notif_title, $notif_body, $conn);
                
                $message = "Success! Added ₦$amount to user wallet.";
                $msg_type = "success";
            } else {
                $message = "Database Error: Could not update wallet.";
                $msg_type = "error";
            }
        } 
        elseif ($type == 'debit') {
            // Update Balance (Subtract)
            $stmt = $conn->prepare("UPDATE wallets SET balance = balance - ? WHERE user_id = ?");
            $stmt->bind_param("di", $amount, $uid);
            
            if ($stmt->execute()) {
                // Log Transaction
                $log = $conn->prepare("INSERT INTO transactions (user_id, trans_ref, reference, amount, status, transaction_type, description, payment_source, created_at) VALUES (?, ?, ?, ?, 'success', 'debit', ?, 'admin', NOW())");
                $log->bind_param("issds", $uid, $reference, $reference, $amount, $reason);
                $log->execute();

                $notif_title = "Wallet Debit: ₦" . number_format($amount);
                $notif_body = "A debit of ₦" . number_format($amount) . " was applied to your wallet. Reason: $reason";

                // ✅ 3. SAVE NOTIFICATION TO DATABASE
                $save_notif = $conn->prepare("INSERT INTO user_notifications (user_id, title, message, created_at, is_read) VALUES (?, ?, ?, NOW(), 0)");
                $save_notif->bind_param("iss", $uid, $notif_title, $notif_body);
                $save_notif->execute();

                // ✅ 4. SEND PUSH NOTIFICATION
                sendPushNotification($uid, $notif_title, $notif_body, $conn);
                
                $message = "Success! Deducted ₦$amount from user wallet.";
                $msg_type = "success";
            } else {
                $message = "Database Error: Could not update wallet.";
                $msg_type = "error";
            }
        }
    }
}

// --- REPLACE THE FUNCTION AT THE BOTTOM OF credit_user.php ---

function sendPushNotification($user_id, $title, $body, $conn) {
    // 1. Get User Token
    $q = $conn->query("SELECT fcm_token FROM users WHERE id = $user_id");
    if ($q->num_rows > 0) {
        $row = $q->fetch_assoc();
        $token = $row['fcm_token'];

        if (!empty($token)) {
            if (function_exists('sendFCMV1')) {
                // Send Notification
                sendFCMV1($token, $title, $body, ["type" => "wallet_update"]);
            } else {
                // If this prints, your fcm_helper.php is not included correctly
                echo "<script>alert('Error: sendFCMV1 function missing! Check include path.');</script>";
            }
        } else {
            // ✅ DEBUG: Tell Admin the token is missing
            echo "<script>alert('Transaction success, but User has NO DEVICE TOKEN. Push not sent. User needs to open the app once.');</script>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fund User Wallet</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f1f5f9; margin: 0; }
        .card { background: white; padding: 40px; border-radius: 12px; width: 100%; max-width: 450px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); }
        h2 { margin-top: 0; color: #1e293b; text-align: center; }
        .user-summary { background: #e2e8f0; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; color: #475569; }
        
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #334155; }
        input, select { width: 100%; padding: 12px; margin-bottom: 20px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 1rem; box-sizing: border-box; }
        input:focus, select:focus { outline: none; border-color: #10b981; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }
        
        button { width: 100%; padding: 15px; background: #10b981; color: white; border: none; font-size: 1rem; font-weight: bold; border-radius: 8px; cursor: pointer; transition: 0.3s; }
        button:hover { background: #059669; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-weight: 500; }
        .alert.success { background: #dcfce7; color: #16a34a; }
        .alert.error { background: #fee2e2; color: #991b1b; }
        
        .back-link { display: block; text-align: center; margin-top: 20px; color: #64748b; text-decoration: none; }
        .back-link:hover { color: #1e293b; }
    </style>
</head>
<body>

    <div class="card">
        <h2>Credit / Debit User</h2>
        
        <?php if($message): ?>
            <div class="alert <?php echo $msg_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <div class="user-summary">
            Managing: <strong><?php echo htmlspecialchars($user_data['username'] ?? 'Unknown User'); ?></strong><br>
            <small><?php echo htmlspecialchars($user_data['email'] ?? ''); ?></small>
        </div>
        
        <form method="POST">
            <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user_id); ?>">
            
            <label>Action Type</label>
            <select name="type">
                <option value="credit">Credit (Add Money)</option>
                <option value="debit">Debit (Remove Money)</option>
            </select>
            
            <label>Amount (₦)</label>
            <input type="number" name="amount" placeholder="e.g. 5000" min="1" step="0.01" required>
            
            <label>Reason / Description</label>
            <input type="text" name="reason" value="Wallet funding by Admin" required>
            
            <button type="submit"><i class="fas fa-paper-plane"></i> Process Transaction</button>
        </form>
        
        <a href="users.php" class="back-link">&larr; Back to User List</a>
    </div>

</body>
</html>