<?php
/**
 * ajax_handler.php - معالج الطلبات الخلفية المتكامل مع SMS و WhatsApp
 * الإصدار: 7.5 - دعم كامل لـ SMS Gateway
 */

if (ob_get_level()) ob_end_clean();
ob_start();

define('SECURE_ACCESS', true);

error_reporting(E_ALL);
ini_set('display_errors', 0); // إخفاء الأخطاء في الإنتاج

$config_path = __DIR__ . '/config.php';
if (!file_exists($config_path)) {
    ob_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => 'ملف الإعدادات غير موجود']);
    exit;
}

require_once $config_path;

if (!isset($conn) || !$conn) {
    ob_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

ob_clean();

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate, private');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$response = ['success' => false, 'message' => 'طلب غير صالح'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : '';
if (empty($action)) {
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

// =============================================
// دوال مساعدة محسنة
// =============================================

function normalizePhoneNumber($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    $phone = ltrim($phone, '0');
    if (strlen($phone) === 9) return '+967' . $phone;
    if (strlen($phone) === 12 && substr($phone, 0, 3) === '967') return '+' . $phone;
    return false;
}

function checkRateLimit($phone, $type = 'otp') {
    $key = "rate_limit_{$type}_" . md5($phone);
    $now = time();
    
    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = [];
    }
    
    $_SESSION[$key] = array_filter($_SESSION[$key], fn($t) => ($now - $t) < 60);
    
    $limit = ($type === 'otp') ? 3 : 10;
    
    if (count($_SESSION[$key]) >= $limit) {
        return false;
    }
    
    $_SESSION[$key][] = $now;
    return true;
}

function generateSecureOTP($length = 6) {
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= mt_rand(0, 9);
    }
    return $otp;
}

function storeOTPInDB($conn, $phone, $otp, $purpose) {
    $expires_at = date('Y-m-d H:i:s', time() + OTP_EXPIRY);
    
    $stmt = $conn->prepare("UPDATE customers SET otp_code = ?, otp_expires_at = ?, sms_status = 'pending', last_sms_sent = NOW(), sms_attempts = 0 WHERE phone = ?");
    $stmt->bind_param("sss", $otp, $expires_at, $phone);
    $result = $stmt->execute();
    $stmt->close();
    
    return $result;
}

function sendSmsOTP($phone, $otp, $name, $purpose = 'verification') {
    $messages = [
        'verification' => "🔐 *مرحباً {$name}*\n\nرمز التحقق الخاص بك هو:\n*📱 {$otp}*\n\n⏰ صالح لمدة 5 دقائق.\n_مطعم ماكس_",
        'reset' => "🔐 *مرحباً {$name}*\n\nرمز إعادة تعيين كلمة المرور هو:\n*📱 {$otp}*\n\n⏰ صالح لمدة 5 دقائق.\n_مطعم ماكس_",
        'welcome' => "🎉 *مرحباً {$name}*\n\n✅ تم تفعيل حسابك في مطعم ماكس بنجاح.\n_مطعم ماكس_"
    ];
    
    $message = $messages[$purpose] ?? $messages['verification'];
    
    // محاولة SMS أولاً
    $smsResult = sendSms($phone, $message);
    
    if ($smsResult['success']) {
        return ['success' => true, 'method' => 'sms'];
    }
    
    // Fallback إلى WhatsApp إذا فشل SMS
    $instanceId = "instance168905";
    $token = "ec6qnfll7uiz5467";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => "https://api.ultramsg.com/{$instanceId}/messages/chat",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query(['token' => $token, 'to' => $phone, 'body' => $message]),
        CURLOPT_TIMEOUT => 30,
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        return ['success' => true, 'method' => 'whatsapp'];
    }
    
    return ['success' => false, 'error' => 'فشل إرسال الرسالة عبر SMS و WhatsApp'];
}

// =============================================
// معالجة الإجراءات
// =============================================

switch ($action) {
    
    case 'register':
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';
        
        if (empty($name) || empty($phone) || empty($address) || empty($password)) {
            $response['message'] = 'جميع الحقول مطلوبة';
            break;
        }
        
        if ($password !== $confirm) {
            $response['message'] = 'كلمات المرور غير متطابقة';
            break;
        }
        
        if (strlen($password) < 6) {
            $response['message'] = 'كلمة المرور يجب أن تكون 6 أحرف على الأقل';
            break;
        }
        
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($phone) !== 9) {
            $response['message'] = 'رقم الهاتف غير صالح';
            break;
        }
        
        $normalizedPhone = '+967' . $phone;
        
        // التحقق من عدم وجود الرقم
        $check = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
        $check->bind_param("s", $normalizedPhone);
        $check->execute();
        if ($check->get_result()->num_rows > 0) {
            $response['message'] = 'رقم الهاتف مسجل مسبقاً';
            $check->close();
            break;
        }
        $check->close();
        
        // التحقق من معدل الطلبات
        if (!checkRateLimit($normalizedPhone, 'otp')) {
            $response['message'] = 'تجاوزت الحد المسموح. حاول بعد دقيقة';
            break;
        }
        
        $otp = generateSecureOTP(6);
        
        // تخزين بيانات التسجيل المؤقتة
        $_SESSION['temp_registration'] = [
            'name' => $name,
            'phone' => $normalizedPhone,
            'address' => $address,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'created_at' => time(),
            'otp' => $otp
        ];
        
        // إرسال OTP عبر SMS و WhatsApp
        $sendResult = sendSmsOTP($normalizedPhone, $otp, $name, 'verification');
        
        if ($sendResult['success']) {
            // تحديث قاعدة البيانات مؤقتاً
            $tempInsert = $conn->prepare("INSERT INTO customers (name, phone, address, password, otp_code, sms_status, created_at) VALUES (?, ?, ?, ?, ?, 'pending', NOW())");
            $tempInsert->bind_param("sssss", $name, $normalizedPhone, $address, $_SESSION['temp_registration']['password'], $otp);
            $tempInsert->execute();
            $tempInsert->close();
            
            $response = [
                'success' => true,
                'needs_verification' => true,
                'phone' => $phone,
                'method' => $sendResult['method'],
                'debug_otp' => (ENVIRONMENT === 'development') ? $otp : null,
                'message' => '✅ تم إرسال رمز التحقق عبر ' . ($sendResult['method'] === 'sms' ? 'رسالة نصية' : 'واتساب')
            ];
        } else {
            $response['message'] = '❌ فشل إرسال رمز التحقق. تأكد من رقم هاتفك';
        }
        break;
    
    case 'verify_otp':
        $user_otp = $_POST['otp'] ?? '';
        $phone = $_POST['phone'] ?? '';
        
        if (empty($user_otp) || empty($phone)) {
            $response['message'] = '❌ بيانات غير صالحة';
            break;
        }
        
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        $normalizedPhone = (strlen($cleanPhone) === 9) ? '+967' . $cleanPhone : $phone;
        
        // التحقق من OTP في قاعدة البيانات
        $stmt = $conn->prepare("SELECT id, name, phone, address, password, otp_code, otp_expires_at, sms_attempts FROM customers WHERE phone = ? AND sms_status = 'pending'");
        $stmt->bind_param("s", $normalizedPhone);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            // التحقق من صلاحية OTP
            if ($row['otp_expires_at'] && strtotime($row['otp_expires_at']) < time()) {
                $response['message'] = '❌ انتهت صلاحية الرمز';
                break;
            }
            
            if ($row['sms_attempts'] >= 5) {
                $response['message'] = '❌ تم تجاوز عدد المحاولات';
                break;
            }
            
            if ($row['otp_code'] === $user_otp) {
                // تحديث حالة العميل
                $update = $conn->prepare("UPDATE customers SET sms_status = 'verified', is_verified = 1, otp_code = NULL, otp_expires_at = NULL WHERE id = ?");
                $update->bind_param("i", $row['id']);
                $update->execute();
                $update->close();
                
                // تسجيل الدخول
                session_regenerate_id(true);
                $_SESSION['customer_id'] = $row['id'];
                $_SESSION['customer_name'] = $row['name'];
                $_SESSION['customer_phone'] = $row['phone'];
                $_SESSION['customer_address'] = $row['address'];
                $_SESSION['valid_session'] = true;
                $_SESSION['session_id'] = session_id();
                
                // إرسال رسالة ترحيب
                sendSmsOTP($normalizedPhone, '', $row['name'], 'welcome');
                
                $response = [
                    'success' => true,
                    'auto_login' => true,
                    'customer_name' => $row['name'],
                    'message' => '✅ تم التسجيل والتحقق بنجاح'
                ];
            } else {
                // زيادة عدد المحاولات
                $update = $conn->prepare("UPDATE customers SET sms_attempts = sms_attempts + 1 WHERE id = ?");
                $update->bind_param("i", $row['id']);
                $update->execute();
                $update->close();
                
                $response['message'] = '❌ رمز غير صحيح';
            }
        } else {
            $response['message'] = '❌ لم يتم العثور على طلب تحقق نشط';
        }
        $stmt->close();
        break;
    
    case 'resend_otp':
        $phone = $_POST['phone'] ?? '';
        
        if (empty($phone)) {
            $response['message'] = '❌ رقم الهاتف مطلوب';
            break;
        }
        
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        $normalizedPhone = (strlen($cleanPhone) === 9) ? '+967' . $cleanPhone : $phone;
        
        if (!checkRateLimit($normalizedPhone, 'otp')) {
            $response['message'] = '❌ تجاوزت الحد المسموح. حاول بعد دقيقة';
            break;
        }
        
        $stmt = $conn->prepare("SELECT id, name FROM customers WHERE phone = ? AND sms_status IN ('pending', 'failed')");
        $stmt->bind_param("s", $normalizedPhone);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $otp = generateSecureOTP(6);
            $expires_at = date('Y-m-d H:i:s', time() + OTP_EXPIRY);
            
            $sendResult = sendSmsOTP($normalizedPhone, $otp, $row['name'], 'verification');
            
            if ($sendResult['success']) {
                $update = $conn->prepare("UPDATE customers SET otp_code = ?, otp_expires_at = ?, sms_status = 'pending', last_sms_sent = NOW(), sms_attempts = 0 WHERE id = ?");
                $update->bind_param("ssi", $otp, $expires_at, $row['id']);
                $update->execute();
                $update->close();
                
                $response = [
                    'success' => true,
                    'method' => $sendResult['method'],
                    'debug_otp' => (ENVIRONMENT === 'development') ? $otp : null,
                    'message' => '✅ تم إعادة إرسال الرمز'
                ];
            } else {
                $response['message'] = '❌ فشل إعادة الإرسال';
            }
        } else {
            $response['message'] = '❌ لم يتم العثور على حساب غير مفعل';
        }
        $stmt->close();
        break;
    
    case 'login':
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        
        if (empty($phone) || empty($password)) {
            $response['message'] = '❌ رقم الهاتف وكلمة المرور مطلوبان';
            break;
        }
        
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($cleanPhone) !== 9) {
            $response['message'] = '❌ رقم الهاتف غير صالح';
            break;
        }
        
        $normalizedPhone = '+967' . $cleanPhone;
        
        $stmt = $conn->prepare("SELECT id, name, phone, address, password, is_verified FROM customers WHERE phone = ?");
        $stmt->bind_param("s", $normalizedPhone);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            if (!$row['is_verified']) {
                $response['message'] = '❌ الحساب غير مفعل. الرجاء التحقق من هاتفك';
                break;
            }
            
            if (password_verify($password, $row['password'])) {
                session_regenerate_id(true);
                $_SESSION['customer_id'] = $row['id'];
                $_SESSION['customer_name'] = $row['name'];
                $_SESSION['customer_phone'] = $row['phone'];
                $_SESSION['customer_address'] = $row['address'];
                $_SESSION['valid_session'] = true;
                $_SESSION['session_id'] = session_id();
                
                $response = [
                    'success' => true,
                    'customer_name' => $row['name'],
                    'message' => '✅ تم تسجيل الدخول بنجاح'
                ];
            } else {
                $response['message'] = '❌ رقم الهاتف أو كلمة المرور غير صحيحة';
            }
        } else {
            $response['message'] = '❌ رقم الهاتف غير مسجل';
        }
        $stmt->close();
        break;
    
    case 'forgot_password':
        $phone = trim($_POST['phone'] ?? '');
        
        if (empty($phone)) {
            $response['message'] = '❌ رقم الهاتف مطلوب';
            break;
        }
        
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($cleanPhone) !== 9) {
            $response['message'] = '❌ رقم الهاتف غير صالح';
            break;
        }
        
        $normalizedPhone = '+967' . $cleanPhone;
        
        $stmt = $conn->prepare("SELECT id, name FROM customers WHERE phone = ? AND is_verified = 1");
        $stmt->bind_param("s", $normalizedPhone);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            if (!checkRateLimit($normalizedPhone, 'otp')) {
                $response['message'] = '❌ تجاوزت الحد المسموح. حاول بعد دقيقة';
                break;
            }
            
            $otp = generateSecureOTP(6);
            $expires_at = date('Y-m-d H:i:s', time() + OTP_EXPIRY);
            
            $sendResult = sendSmsOTP($normalizedPhone, $otp, $row['name'], 'reset');
            
            if ($sendResult['success']) {
                $update = $conn->prepare("UPDATE customers SET otp_code = ?, otp_expires_at = ?, sms_status = 'pending' WHERE id = ?");
                $update->bind_param("ssi", $otp, $expires_at, $row['id']);
                $update->execute();
                $update->close();
                
                $_SESSION['reset_data'] = [
                    'id' => $row['id'],
                    'phone' => $normalizedPhone,
                    'name' => $row['name'],
                    'otp' => $otp,
                    'created_at' => time()
                ];
                
                $response = [
                    'success' => true,
                    'phone' => $cleanPhone,
                    'method' => $sendResult['method'],
                    'debug_otp' => (ENVIRONMENT === 'development') ? $otp : null,
                    'message' => '✅ تم إرسال رمز إعادة التعيين'
                ];
            } else {
                $response['message'] = '❌ فشل إرسال الرمز';
            }
        } else {
            $response['message'] = '❌ رقم الهاتف غير مسجل أو غير مفعل';
        }
        $stmt->close();
        break;
    
    case 'verify_reset_otp':
        $user_otp = $_POST['otp'] ?? '';
        $phone = $_POST['phone'] ?? '';
        
        if (empty($user_otp) || empty($phone)) {
            $response['message'] = '❌ بيانات غير صالحة';
            break;
        }
        
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        $normalizedPhone = (strlen($cleanPhone) === 9) ? '+967' . $cleanPhone : $phone;
        
        $stmt = $conn->prepare("SELECT id, otp_code, otp_expires_at, sms_attempts FROM customers WHERE phone = ? AND sms_status = 'pending'");
        $stmt->bind_param("s", $normalizedPhone);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            if (strtotime($row['otp_expires_at']) < time()) {
                $response['message'] = '❌ انتهت صلاحية الرمز';
                break;
            }
            
            if ($row['sms_attempts'] >= 5) {
                $response['message'] = '❌ تم تجاوز عدد المحاولات';
                break;
            }
            
            if ($row['otp_code'] === $user_otp) {
                $_SESSION['reset_allowed'] = true;
                $_SESSION['reset_allowed_phone'] = $normalizedPhone;
                $_SESSION['reset_allowed_time'] = time();
                
                $response = [
                    'success' => true,
                    'message' => '✅ تم التحقق من الرمز بنجاح'
                ];
            } else {
                $update = $conn->prepare("UPDATE customers SET sms_attempts = sms_attempts + 1 WHERE id = ?");
                $update->bind_param("i", $row['id']);
                $update->execute();
                $update->close();
                
                $response['message'] = '❌ رمز غير صحيح';
            }
        } else {
            $response['message'] = '❌ لم يتم العثور على طلب إعادة تعيين نشط';
        }
        $stmt->close();
        break;
    
    case 'reset_password':
        $phone = $_POST['phone'] ?? '';
        $password = $_POST['password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';
        
        if (empty($phone) || empty($password) || empty($confirm)) {
            $response['message'] = '❌ جميع الحقول مطلوبة';
            break;
        }
        
        if ($password !== $confirm) {
            $response['message'] = '❌ كلمات المرور غير متطابقة';
            break;
        }
        
        if (strlen($password) < 6) {
            $response['message'] = '❌ كلمة المرور يجب أن تكون 6 أحرف على الأقل';
            break;
        }
        
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        $normalizedPhone = (strlen($cleanPhone) === 9) ? '+967' . $cleanPhone : $phone;
        
        if (!isset($_SESSION['reset_allowed']) || $_SESSION['reset_allowed'] !== true) {
            $response['message'] = '❌ لم يتم التحقق من الرمز';
            break;
        }
        
        if ($_SESSION['reset_allowed_phone'] !== $normalizedPhone) {
            $response['message'] = '❌ جلسة غير صالحة';
            break;
        }
        
        if ((time() - $_SESSION['reset_allowed_time']) > 600) {
            unset($_SESSION['reset_allowed'], $_SESSION['reset_allowed_phone'], $_SESSION['reset_allowed_time']);
            $response['message'] = '❌ انتهت صلاحية التحقق';
            break;
        }
        
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $update = $conn->prepare("UPDATE customers SET password = ?, sms_status = 'verified', otp_code = NULL, otp_expires_at = NULL WHERE phone = ?");
        $update->bind_param("ss", $hashed_password, $normalizedPhone);
        
        if ($update->execute()) {
            $stmt = $conn->prepare("SELECT id, name FROM customers WHERE phone = ?");
            $stmt->bind_param("s", $normalizedPhone);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            
            session_regenerate_id(true);
            $_SESSION['customer_id'] = $user['id'];
            $_SESSION['customer_name'] = $user['name'];
            $_SESSION['customer_phone'] = $normalizedPhone;
            $_SESSION['valid_session'] = true;
            
            unset($_SESSION['reset_data'], $_SESSION['reset_allowed'], $_SESSION['reset_allowed_phone'], $_SESSION['reset_allowed_time']);
            
            $response = [
                'success' => true,
                'auto_login' => true,
                'customer_name' => $user['name'],
                'message' => '✅ تم تغيير كلمة المرور بنجاح'
            ];
        } else {
            $response['message'] = '❌ فشل تغيير كلمة المرور';
        }
        $update->close();
        break;
    
    case 'check_auth':
        $response = [
            'success' => true,
            'logged_in' => isset($_SESSION['customer_id']) && isset($_SESSION['valid_session']),
            'customer_name' => $_SESSION['customer_name'] ?? '',
            'customer_phone' => $_SESSION['customer_phone'] ?? ''
        ];
        break;
    
    case 'add_to_cart':
        if (!isset($_SESSION['customer_id'])) {
            $response['message'] = '❌ الرجاء تسجيل الدخول أولاً';
            break;
        }
        
        $meal_id = intval($_POST['meal_id'] ?? 0);
        $portion_id = intval($_POST['portion_id'] ?? 0);
        $quantity = max(1, intval($_POST['quantity'] ?? 1));
        $meal_name = trim($_POST['meal_name'] ?? 'وجبة');
        $portion_price = floatval($_POST['portion_price'] ?? 0);
        
        if ($meal_id > 0 && $quantity > 0) {
            if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];
            
            $cart_key = $meal_id . '_' . $portion_id;
            
            if (isset($_SESSION['cart'][$cart_key])) {
                $_SESSION['cart'][$cart_key]['quantity'] += $quantity;
            } else {
                $_SESSION['cart'][$cart_key] = [
                    'meal_id' => $meal_id,
                    'portion_id' => $portion_id,
                    'quantity' => $quantity,
                    'name' => $meal_name,
                    'price' => $portion_price,
                    'added_at' => time()
                ];
            }
            
            $total_count = array_sum(array_column($_SESSION['cart'], 'quantity'));
            
            $response = [
                'success' => true,
                'cart_count' => $total_count,
                'message' => '✅ تمت الإضافة للسلة'
            ];
        } else {
            $response['message'] = '❌ بيانات غير صالحة';
        }
        break;
    
    case 'get_portions':
        $meal_id = intval($_POST['meal_id'] ?? 0);
        if ($meal_id <= 0) {
            $response['message'] = '❌ معرف وجبة غير صالح';
            break;
        }
        
        $portions = [];
        $stmt = $conn->prepare("SELECT id, name, price FROM meal_portions WHERE meal_id = ? AND is_active = 1 ORDER BY price");
        $stmt->bind_param("i", $meal_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $portions[] = $row;
        }
        $stmt->close();
        
        $response = ['success' => true, 'portions' => $portions];
        break;
    
    case 'logout':
        session_destroy();
        $response = ['success' => true, 'message' => '✅ تم تسجيل الخروج بنجاح'];
        break;
    
    default:
        $response['message'] = '❌ إجراء غير معروف: ' . $action;
}

ob_clean();
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
?>