<?php
require_once __DIR__ . '/../config/config.php';

// Get user by mobile
function getUserByMobile($mobile) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT * FROM users WHERE mobile = ?");
    $stmt->bind_param("s", $mobile);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    $conn->close();
    return $user;
}

// Get user by email
function getUserByEmail($email) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    $conn->close();
    return $user;
}

// Create new user
function createUser($mobile, $email, $password, $name = null) {
    $conn = getDBConnection();
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("INSERT INTO users (name, mobile, email, password) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $name, $mobile, $email, $hashedPassword);
    $result = $stmt->execute();
    $userId = $conn->insert_id;
    $stmt->close();
    $conn->close();
    return $result ? $userId : false;
}

// Login user
function loginUser($mobile, $password) {
    $user = getUserByMobile($mobile);
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['mobile'] = $user['mobile'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['is_admin'] = $user['is_admin'];
        return true;
    }
    return false;
}

// Get user orders
function getUserOrders($userId, $status = null) {
    $conn = getDBConnection();
    if ($status) {
        $stmt = $conn->prepare("SELECT 
            id, user_id, country_code, country_name, package_name, package_code, 
            data_amount, validity_days, price_usd, price_irr, status, 
            payment_authority, esim_id, iccid, qr_code, activation_code, 
            esim_status, created_at 
            FROM orders 
            WHERE user_id = ? AND status = ? 
            ORDER BY created_at DESC");
        $stmt->bind_param("is", $userId, $status);
    } else {
        $stmt = $conn->prepare("SELECT 
            id, user_id, country_code, country_name, package_name, package_code, 
            data_amount, validity_days, price_usd, price_irr, status, 
            payment_authority, esim_id, iccid, qr_code, activation_code, 
            esim_status, created_at 
            FROM orders 
            WHERE user_id = ? 
            ORDER BY created_at DESC");
        $stmt->bind_param("i", $userId);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $orders = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $conn->close();
    return $orders;
}

// Create order
function createOrder($userId, $packageData, $priceUsd) {
    $conn = getDBConnection();
    $priceIrr = usdToIrr($priceUsd);

    $stmt = $conn->prepare("INSERT INTO orders (user_id, country_code, country_name, package_name, package_code, data_amount, validity_days, price_usd, price_irr, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')");
    $stmt->bind_param("isssssiid",
        $userId,
        $packageData['country_code'],
        $packageData['country_name'],
        $packageData['package_name'],
        $packageData['package_code'],
        $packageData['data_amount'],
        $packageData['validity_days'],
        $priceUsd,
        $priceIrr
    );
    $result = $stmt->execute();
    $orderId = $conn->insert_id;
    $stmt->close();
    $conn->close();
    return $result ? $orderId : false;
}

// Update order payment
function updateOrderPayment($orderId, $authority) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("UPDATE orders SET payment_authority = ? WHERE id = ?");
    $stmt->bind_param("si", $authority, $orderId);
    $result = $stmt->execute();
    $stmt->close();
    $conn->close();
    return $result;
}

// Complete order
function completeOrder($orderId, $refId, $esimData) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("UPDATE orders SET status = 'paid', payment_ref_id = ?, iccid = ?, qr_code = ?, activation_code = ?, paid_at = NOW() WHERE id = ?");
    $stmt->bind_param("ssssi", 
        $refId,
        $esimData['iccid'],
        $esimData['qr_code'],
        $esimData['activation_code'],
        $orderId
    );
    $result = $stmt->execute();
    $stmt->close();
    $conn->close();
    return $result;
}

// Get order by ID
function getOrderById($orderId) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->bind_param("i", $orderId);
    $stmt->execute();
    $result = $stmt->get_result();
    $order = $result->fetch_assoc();
    $stmt->close();
    $conn->close();
    return $order;
}

// Get order by authority
function getOrderByAuthority($authority) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT * FROM orders WHERE payment_authority = ?");
    $stmt->bind_param("s", $authority);
    $stmt->execute();
    $result = $stmt->get_result();
    $order = $result->fetch_assoc();
    $stmt->close();
    $conn->close();
    return $order;
}

// Get all users (for admin)
function getAllUsers() {
    $conn = getDBConnection();
    $result = $conn->query("SELECT id, mobile, email, created_at, is_admin FROM users ORDER BY created_at DESC");
    $users = $result->fetch_all(MYSQLI_ASSOC);
    $conn->close();
    return $users;
}

// Get all orders (for admin)
function getAllOrders($limit = null) {
    $conn = getDBConnection();
    $sql = "SELECT o.*, u.mobile, u.email as user_email FROM orders o JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC";
    if ($limit) {
        $sql .= " LIMIT " . intval($limit);
    }
    $result = $conn->query($sql);
    $orders = $result->fetch_all(MYSQLI_ASSOC);
    $conn->close();
    return $orders;
}

// Format date to Jalali (Persian)
function toJalali($timestamp) {
    // Simple Jalali conversion (you can use a library for more accuracy)
    return jdate('Y/m/d H:i', $timestamp);
}

// Jalali date function (basic implementation)
function jdate($format, $timestamp = null) {
    if ($timestamp === null) {
        $timestamp = time();
    }
    
    // This is a placeholder - in production, use a proper Jalali date library
    return date($format, $timestamp);
}

// Note: sanitize(), validateMobile(), and validateEmail() are defined in config.php

// ==================== OTP Functions ====================

/**
 * ایجاد و ارسال کد OTP
 */
function createAndSendOTP($mobile, $type = 'login') {
    require_once __DIR__ . '/../api/sms-api.php';
    
    $conn = getDBConnection();
    $mobile = sanitize($mobile);
    
    // حذف OTP های قبلی این شماره
    $stmt = $conn->prepare("DELETE FROM otp_codes WHERE mobile = ? AND type = ?");
    $stmt->bind_param("ss", $mobile, $type);
    $stmt->execute();
    $stmt->close();
    
    // تولید کد OTP
    $code = SmsAPI::generateOTP();
    
    // زمان انقضا (5 دقیقه)
    $expiresAt = date('Y-m-d H:i:s', time() + 300);
    
    // ذخیره در دیتابیس
    $stmt = $conn->prepare("INSERT INTO otp_codes (mobile, code, type, expires_at) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $mobile, $code, $type, $expiresAt);
    $result = $stmt->execute();
    $stmt->close();
    $conn->close();
    
    if (!$result) {
        return [
            'success' => false,
            'message' => 'خطا در ذخیره کد تایید'
        ];
    }
    
    // ارسال پیامک
    $sms = new SmsAPI();
    $smsResult = $sms->sendOTP($mobile, $code);
    
    if ($smsResult['success']) {
        // اگر در حالت تست است، کد را در پیغام نشان بده
        $message = 'کد تایید به شماره ' . $mobile . ' ارسال شد';
        if (isset($smsResult['test_mode']) && $smsResult['test_mode']) {
            $message = '🔑 کد تایید شما: <strong style="font-size: 1.5rem; color: #28a745;">' . $code . '</strong><br><small style="color: #666;">(حالت تست - پیامک ارسال نشد)</small>';
        }
        
        return [
            'success' => true,
            'message' => $message,
            'expires_in' => 300, // 5 minutes
            'code' => isset($smsResult['test_mode']) ? $code : null // فقط در حالت تست
        ];
    } else {
        return [
            'success' => false,
            'message' => 'خطا در ارسال پیامک: ' . ($smsResult['message'] ?? 'خطای ناشناخته')
        ];
    }
}

/**
 * بررسی صحت کد OTP
 */
function verifyOTP($mobile, $code, $type = 'login') {
    $conn = getDBConnection();
    $mobile = sanitize($mobile);
    $code = sanitize($code);
    
    // جستجوی کد
    $stmt = $conn->prepare("SELECT * FROM otp_codes WHERE mobile = ? AND code = ? AND type = ? AND is_used = 0 AND expires_at > NOW() ORDER BY created_at DESC LIMIT 1");
    $stmt->bind_param("sss", $mobile, $code, $type);
    $stmt->execute();
    $result = $stmt->get_result();
    $otp = $result->fetch_assoc();
    $stmt->close();
    
    if (!$otp) {
        $conn->close();
        return [
            'success' => false,
            'message' => 'کد تایید نامعتبر یا منقضی شده است'
        ];
    }
    
    // علامت‌گذاری به عنوان استفاده شده
    $stmt = $conn->prepare("UPDATE otp_codes SET is_used = 1 WHERE id = ?");
    $stmt->bind_param("i", $otp['id']);
    $stmt->execute();
    $stmt->close();
    $conn->close();
    
    return [
        'success' => true,
        'message' => 'کد تایید صحیح است'
    ];
}

/**
 * لاگین با OTP
 */
function loginWithOTP($mobile, $code) {
    // بررسی کد OTP
    $verification = verifyOTP($mobile, $code, 'login');
    
    if (!$verification['success']) {
        return $verification;
    }
    
    // جستجوی کاربر
    $user = getUserByMobile($mobile);
    
    if (!$user) {
        return [
            'success' => false,
            'message' => 'کاربری با این شماره موبایل یافت نشد. لطفاً ابتدا ثبت‌نام کنید.'
        ];
    }
    
    // ایجاد session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['mobile'] = $user['mobile'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['name'] = $user['name'];
    $_SESSION['is_admin'] = $user['is_admin'];
    
    return [
        'success' => true,
        'message' => 'ورود موفقیت‌آمیز'
    ];
}

/**
 * ثبت‌نام با OTP
 */
function registerWithOTP($mobile, $code, $email = null, $name = null) {
    // بررسی کد OTP
    $verification = verifyOTP($mobile, $code, 'register');
    
    if (!$verification['success']) {
        return $verification;
    }
    
    // بررسی وجود کاربر
    if (getUserByMobile($mobile)) {
        return [
            'success' => false,
            'message' => 'این شماره موبایل قبلاً ثبت شده است'
        ];
    }
    
    // ایجاد کاربر جدید
    $conn = getDBConnection();
    
    // اگر ایمیل وارد نشده، یک ایمیل پیش‌فرض بساز
    if (empty($email)) {
        $email = $mobile . '@esim.local';
    }
    
    // رمز عبور تصادفی (کاربر با OTP لاگین می‌کند)
    $randomPassword = bin2hex(random_bytes(16));
    $hashedPassword = password_hash($randomPassword, PASSWORD_DEFAULT);
    
    $stmt = $conn->prepare("INSERT INTO users (name, mobile, email, password) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $name, $mobile, $email, $hashedPassword);
    $result = $stmt->execute();
    $userId = $conn->insert_id;
    $stmt->close();
    $conn->close();
    
    if (!$result) {
        return [
            'success' => false,
            'message' => 'خطا در ثبت‌نام'
        ];
    }
    
    // ایجاد session
    $_SESSION['user_id'] = $userId;
    $_SESSION['mobile'] = $mobile;
    $_SESSION['email'] = $email;
    $_SESSION['name'] = $name;
    $_SESSION['is_admin'] = 0;
    
    return [
        'success' => true,
        'message' => 'ثبت‌نام موفقیت‌آمیز'
    ];
}