<?php
// api.php - Modified to work like your working backend
session_start();
require 'db.php';

// AJAX field validations

// Username check
if (isset($_POST['check_username'])) {
    $username = $_POST['username'];
    $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();
    echo $stmt->num_rows > 0 ? "exists" : "available";
    exit;
}

// Email check
if (isset($_POST['check_email'])) {
    $email = $_POST['email'];
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    echo $stmt->num_rows > 0 ? "exists" : "available";
    exit;
}

// Phone check
if (isset($_POST['check_phone'])) {
    $phone = $_POST['phone'];
    $stmt = $conn->prepare("SELECT id FROM users WHERE phone = ?");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $stmt->store_result();
    echo $stmt->num_rows > 0 ? "exists" : "available";
    exit;
}

// Process form submissions via AJAX
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ajax'])) {
    if ($_POST['form_type'] == 'register') {
        // Registration with first name and last name
        $first_name    = trim($_POST['first_name']);
        $last_name     = trim($_POST['last_name']);
        $username      = trim($_POST['username']);
        $email         = $_POST['email'];
        $phone         = $_POST['phone'];
        $password      = $_POST['password'];
        $referred_by   = $_POST['referred_by'] ?? NULL;
        $referral_code = strtoupper(substr(md5(uniqid()), 0, 6));

        if (empty($first_name) || empty($last_name) || empty($username) || empty($email) || empty($phone) || empty($password)) {
            echo json_encode(['success' => false, 'message' => "Please fill in all fields."]);
            exit;
        }

        // Username: at least 5 characters with no spaces.
        if (strlen($username) < 5 || preg_match('/\s/', $username)) {
            echo json_encode(['success' => false, 'message' => "Invalid username! Must be at least 5 characters with no spaces."]);
            exit;
        }

        // Password: at least 8 characters long.
        if (strlen($password) < 8) {
            echo json_encode(['success' => false, 'message' => "Password must be at least 8 characters long."]);
            exit;
        }

        // Check if username already exists
        $check_username = $conn->prepare("SELECT id FROM users WHERE username = ?");
        $check_username->bind_param("s", $username);
        $check_username->execute();
        $check_username->store_result();
        if ($check_username->num_rows > 0) {
            echo json_encode(['success' => false, 'message' => "Username already exists!"]);
            exit;
        }

        // Check if email already exists
        $check_email = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $check_email->bind_param("s", $email);
        $check_email->execute();
        $check_email->store_result();
        if ($check_email->num_rows > 0) {
            echo json_encode(['success' => false, 'message' => "Email already exists!"]);
            exit;
        }

        $hashed_password = password_hash($password, PASSWORD_BCRYPT);

        // Start transaction for registration and wallet creation
        $conn->begin_transaction();

        try {
            $query = "INSERT INTO users (first_name, last_name, username, email, phone, password, referral_code, referred_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("ssssssss", $first_name, $last_name, $username, $email, $phone, $hashed_password, $referral_code, $referred_by);

            if ($stmt->execute()) {
                $user_id = $conn->insert_id;
                
                // Create wallet for new user
                $walletStmt = $conn->prepare("INSERT INTO wallets (user_id, balance, referral_commission, referral_count, created_at, updated_at) VALUES (?, 0, 0, 0, NOW(), NOW())");
                $walletStmt->bind_param("i", $user_id);
                $walletStmt->execute();
                
                // Process referral if referred_by is provided
                if (!empty($referred_by)) {
                    // Initialize referral system and process referral
                    $referralSystem = new ReferralSystem($conn);
                    $referralResult = $referralSystem->processSignupReferral($user_id, $referred_by);
                    
                    if ($referralResult['success']) {
                        error_log("🎉 Referral bonus credited: " . $referralResult['message']);
                    } else {
                        error_log("⚠️ Referral processing failed: " . $referralResult['message']);
                    }
                }

                // Commit transaction
                $conn->commit();
                
                $_SESSION['user_id'] = $user_id;
                $_SESSION['username'] = $username;
                echo json_encode([
                    'success' => true, 
                    'message' => "Registration successful!", 
                    'redirect' => "dashboard.php",
                    'user_id' => $user_id,
                    'username' => $username,
                    'referral_code' => $referral_code
                ]);
                exit;
            } else {
                throw new Exception("Registration failed: " . $stmt->error);
            }
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => "Registration failed! Try again."]);
            exit;
        }
    } elseif ($_POST['form_type'] == 'login') {
        // AJAX login
        $username = $_POST['username'];
        $password = $_POST['password'];

        $query = "SELECT id, username, password, first_name, last_name, email, phone, referred_by, referral_code, referral_count FROM users WHERE username=?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            
            // Get referral stats
            $referralSystem = new ReferralSystem($conn);
            $referralStats = $referralSystem->getReferralStats($user['id']);
            
            echo json_encode([
                'success' => true, 
                'message' => "Login successful!", 
                'redirect' => "dashboard.php",
                'user_id' => $user['id'],
                'username' => $user['username'],
                'first_name' => $user['first_name'],
                'last_name' => $user['last_name'],
                'email' => $user['email'],
                'phone' => $user['phone'],
                'referred_by' => $user['referred_by'],
                'referral_code' => $user['referral_code'],
                'referral_count' => $user['referral_count'],
                'referral_stats' => $referralStats
            ]);
            exit;
        } else {
            echo json_encode(['success' => false, 'message' => "Invalid username or password."]);
            exit;
        }
    }
}

// === REFERRAL SYSTEM CLASS ===
class ReferralSystem {
    private $conn;
    private $signupBonus = 20.00;
    private $dataPurchaseBonus = 1.00;

    public function __construct($connection) {
        $this->conn = $connection;
    }

    // Process referral when new user registers
    public function processSignupReferral($referredUserId, $referrerUsername) {
        try {
            // Find referrer by username
            $referrer = $this->findUserByUsername($referrerUsername);
            
            if (!$referrer) {
                throw new Exception("Referrer not found");
            }

            // Credit referrer's wallet with N20 and increment referral count
            $creditResult = $this->creditReferrerWallet($referrer['id'], $this->signupBonus, "referral_signup", $referredUserId);
            
            if (!$creditResult) {
                throw new Exception("Failed to credit referrer wallet");
            }

            // Update referral stats for referrer
            $this->updateReferralStats($referrer['id']);

            return [
                'success' => true,
                'message' => 'Referral bonus credited successfully',
                'referrer_id' => $referrer['id'],
                'referrer_username' => $referrer['username'],
                'bonus' => $this->signupBonus
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    private function findUserByUsername($username) {
        $stmt = $this->conn->prepare("SELECT id, username, referral_code FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    private function findUserById($userId) {
        $stmt = $this->conn->prepare("SELECT id, username, referred_by FROM users WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    private function creditReferrerWallet($referrerId, $amount, $type, $referredUserId) {
        try {
            // Get or create wallet for REFERRER
            $wallet = $this->getOrCreateWallet($referrerId);
            
            if (!$wallet) {
                return false;
            }

            // Update REFERRER's wallet
            $stmt = $this->conn->prepare("
                UPDATE wallets 
                SET balance = balance + ?, 
                    referral_commission = referral_commission + ?,
                    referral_count = referral_count + 1,
                    updated_at = NOW() 
                WHERE user_id = ?
            ");
            $stmt->bind_param("ddi", $amount, $amount, $referrerId);
            $updateResult = $stmt->execute();
            
            if (!$updateResult) {
                return false;
            }

            // Record referral transaction
            $transactionResult = $this->recordReferralTransaction($referrerId, $referredUserId, $amount, $type);
            
            return $transactionResult;

        } catch (Exception $e) {
            return false;
        }
    }

    private function getOrCreateWallet($userId) {
        // Check if wallet exists
        $stmt = $this->conn->prepare("SELECT * FROM wallets WHERE user_id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $wallet = $result->fetch_assoc();

        if (!$wallet) {
            // Create new wallet
            $stmt = $this->conn->prepare("
                INSERT INTO wallets (user_id, balance, referral_commission, referral_count, created_at, updated_at) 
                VALUES (?, 0, 0, 0, NOW(), NOW())
            ");
            $stmt->bind_param("i", $userId);
            $insertResult = $stmt->execute();
            
            if ($insertResult) {
                return ['user_id' => $userId, 'balance' => 0, 'referral_commission' => 0, 'referral_count' => 0];
            } else {
                return null;
            }
        }
        return $wallet;
    }

    private function recordReferralTransaction($referrerId, $referredUserId, $amount, $type) {
        try {
            $stmt = $this->conn->prepare("
                INSERT INTO referral_transactions (referrer_id, referred_user_id, amount, type, status, created_at) 
                VALUES (?, ?, ?, ?, 'completed', NOW())
            ");
            $stmt->bind_param("iids", $referrerId, $referredUserId, $amount, $type);
            return $stmt->execute();
        } catch (Exception $e) {
            return false;
        }
    }

    private function updateReferralStats($referrerId) {
        $stmt = $this->conn->prepare("
            UPDATE users 
            SET referral_count = (
                SELECT COUNT(*) FROM users WHERE referred_by = (
                    SELECT username FROM users WHERE id = ?
                )
            ), 
            updated_at = NOW() 
            WHERE id = ?
        ");
        $stmt->bind_param("ii", $referrerId, $referrerId);
        $stmt->execute();
    }

    // Get referral statistics
    public function getReferralStats($userId) {
        $stmt = $this->conn->prepare("
            SELECT 
                u.username,
                u.referral_count as user_referral_count,
                u.referral_code,
                u.referred_by,
                COALESCE((
                    SELECT SUM(amount) 
                    FROM referral_transactions 
                    WHERE referrer_id = ? AND status = 'completed'
                ), 0) as total_earnings,
                COALESCE(w.balance, 0) as wallet_balance,
                COALESCE(w.referral_commission, 0) as total_referral_commission,
                COALESCE(w.referral_count, 0) as wallet_referral_count
            FROM users u
            LEFT JOIN wallets w ON u.id = w.user_id
            WHERE u.id = ?
        ");
        $stmt->bind_param("ii", $userId, $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        return $result->fetch_assoc();
    }

    // Process data purchase referral bonus
    public function processDataPurchaseReferral($buyerUserId, $purchaseAmount) {
        try {
            // Get buyer info to find referrer
            $buyer = $this->findUserById($buyerUserId);
            
            if (!$buyer || empty($buyer['referred_by'])) {
                return ['success' => false, 'message' => 'No referrer found'];
            }

            // Find referrer by username
            $referrer = $this->findUserByUsername($buyer['referred_by']);
            
            if (!$referrer) {
                return ['success' => false, 'message' => 'Referrer not found'];
            }

            // Credit REFERRER with N1 for data purchase
            $creditResult = $this->creditReferrerWallet($referrer['id'], $this->dataPurchaseBonus, "data_purchase_commission", $buyerUserId);

            if ($creditResult) {
                // Update referral stats
                $this->updateReferralStats($referrer['id']);

                return [
                    'success' => true,
                    'message' => 'Data purchase commission credited',
                    'referrer_id' => $referrer['id'],
                    'commission' => $this->dataPurchaseBonus,
                    'buyer_id' => $buyerUserId
                ];
            } else {
                throw new Exception("Failed to credit data purchase commission");
            }

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}

// Additional endpoints for session checking, logout, etc.
if (isset($_GET['check_session'])) {
    if (isset($_SESSION['user_id'])) {
        echo json_encode([
            'success' => true,
            'user_id' => $_SESSION['user_id'],
            'username' => $_SESSION['username']
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Not logged in']);
    }
    exit;
}

if (isset($_GET['logout'])) {
    session_destroy();
    echo json_encode(['success' => true, 'message' => 'Logged out successfully']);
    exit;
}

// Default response for invalid requests
echo json_encode(['success' => false, 'message' => 'Invalid request']);
exit;
?>