<?php
session_start();
require_once '../../config/database.php';

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Log the request
error_log("=== Order Create Request ===");
error_log("POST Data: " . print_r($_POST, true));
error_log("Session User ID: " . ($_SESSION['user_id'] ?? 'NOT SET'));

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    error_log("ERROR: User not logged in");
    $_SESSION['error'] = 'يجب تسجيل الدخول أولاً';
    header('Location: ../../public/login.php');
    exit;
}

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    // جلب بيانات الفورم
    $user_id = $_SESSION['user_id'];
    
    // Check if using saved address or new address
    $address_id = $_POST['address_id'] ?? null;
    
    if ($address_id) {
        // Get address from database
        $stmt = $conn->prepare("SELECT * FROM user_addresses WHERE id = ? AND user_id = ?");
        $stmt->execute([$address_id, $user_id]);
        $saved_address = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($saved_address) {
            // Use saved address with user info from hidden fields
            $customer_name = $_POST['user_name'] ?? '';
            $phone = $_POST['user_phone'] ?? '';
            $email = $_POST['user_email'] ?? '';
            $address = $saved_address['address'];
            $city = $saved_address['label']; // Using label as city for now
            $postal_code = '';
            
            error_log("Using saved address ID: $address_id - Email: $email");
        } else {
            error_log("ERROR: Address ID $address_id not found");
            $_SESSION['error'] = 'العنوان غير موجود';
            header('Location: ../../public/checkout.php');
            exit;
        }
    } else {
        // Use form data
        $customer_name = $_POST['full_name'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $email = $_POST['email'] ?? '';
        $address = $_POST['address_line1'] ?? '';
        $city = $_POST['city'] ?? '';
        $postal_code = $_POST['postal_code'] ?? '';
        
        error_log("Using new address from form - Email: $email");
    }
    
    // Final fallback: get from database if still empty
    if (empty($email) || empty($customer_name) || empty($phone)) {
        $stmt = $conn->prepare("SELECT name, phone, email FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (empty($email)) $email = $user_info['email'] ?? '';
        if (empty($customer_name)) $customer_name = $user_info['name'] ?? '';
        if (empty($phone)) $phone = $user_info['phone'] ?? '';
        
        error_log("Applied fallback from database - Email: $email");
    }
    
    $notes = $_POST['notes'] ?? '';
    $payment_method = $_POST['payment_method'] ?? 'cod';
    $coupon_code = $_POST['coupon_code'] ?? null;
    
    // التحقق من الحقول المطلوبة (email is optional)
    error_log("Validating fields - Name: $customer_name, Phone: $phone, Email: $email, Address: $address, City: $city");
    
    if (empty($customer_name) || empty($phone) || empty($address) || empty($city)) {
        error_log("ERROR: Missing required fields");
        $_SESSION['error'] = 'الرجاء ملء جميع الحقول المطلوبة (الاسم، الجوال، العنوان، المدينة)';
        header('Location: ../../public/checkout.php');
        exit;
    }
    
    // Set default email if empty
    if (empty($email)) {
        $email = 'customer' . $user_id . '@rozskin.local';
        error_log("Email was empty, using default: $email");
    }
    
    error_log("✓ All required fields present");
    
    // جلب عناصر السلة
    $stmt = $conn->prepare("
        SELECT c.*, p.name, p.price 
        FROM cart c 
        JOIN products p ON c.product_id = p.id 
        WHERE c.user_id = ?
    ");
    $stmt->execute([$user_id]);
    $cart_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($cart_items)) {
        $_SESSION['error'] = 'السلة فارغة';
        header('Location: ../../public/cart.php');
        exit;
    }
    
    // حساب الإجمالي
    $subtotal = 0;
    foreach ($cart_items as $item) {
        $subtotal += $item['price'] * $item['quantity'];
    }
    
    $shipping = 0;
    $tax = $subtotal * 0.15;
    $discount = 0;
    
    // تطبيق الكوبون إن وجد
    if (isset($_SESSION['applied_coupon'])) {
        $discount = $_SESSION['applied_coupon']['discount'];
    }
    
    $total = $subtotal + $shipping + $tax - $discount;
    
    // بدء Transaction
    $conn->beginTransaction();
    
    // Split customer name
    $name_parts = explode(' ', $customer_name, 2);
    $first_name = $name_parts[0];
    $last_name = isset($name_parts[1]) ? $name_parts[1] : '';
    
    // إنشاء الطلب
    $order_number = 'ORD-' . date('Ymd') . '-' . rand(1000, 9999);
    
    $stmt = $conn->prepare("
        INSERT INTO orders (
            user_id, order_number, first_name, last_name, phone, email, 
            address, city, postal_code, notes, payment_method, 
            subtotal, shipping, tax, discount, total, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    ");
    
    $stmt->execute([
        $user_id, 
        $order_number, 
        $first_name, 
        $last_name, 
        $phone, 
        $email,
        $address, 
        $city, 
        $postal_code, 
        $notes, 
        $payment_method,
        $subtotal, 
        $shipping, 
        $tax, 
        $discount, 
        $total
    ]);
    
    $order_id = $conn->lastInsertId();
    
    // إضافة عناصر الطلب
    $stmt = $conn->prepare("
        INSERT INTO order_items (order_id, product_id, product_name, price, quantity, total)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    
    foreach ($cart_items as $item) {
        $item_total = $item['price'] * $item['quantity'];
        $stmt->execute([
            $order_id,
            $item['product_id'],
            $item['name'],
            $item['price'],
            $item['quantity'],
            $item_total
        ]);
    }
    
    // Save address if requested
    if (!$address_id && isset($_POST['save_address']) && $_POST['save_address'] == '1') {
        try {
            $label = $city; // Use city as label
            $full_address = $address . ', ' . $city;
            if ($postal_code) {
                $full_address .= ', ' . $postal_code;
            }
            
            $stmt = $conn->prepare("INSERT INTO user_addresses (user_id, label, address, is_default, created_at) VALUES (?, ?, ?, 0, NOW())");
            $stmt->execute([$user_id, $label, $full_address]);
        } catch (Exception $e) {
            // Don't fail the order if address save fails
            error_log("Failed to save address: " . $e->getMessage());
        }
    }
    
    // حذف السلة
    $stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
    $stmt->execute([$user_id]);
    
    // حذف الكوبون المطبق
    unset($_SESSION['applied_coupon']);
    
    // Commit Transaction
    $conn->commit();
    
    // Send Enhanced Telegram notification
    try {
        require_once '../../helpers/telegram-notifications.php';
        notifyNewOrder($order_id);
    } catch (Exception $e) {
        // Log error but don't stop the order process
        error_log("Telegram notification failed: " . $e->getMessage());
    }
    
    // Redirect to success page
    error_log("✓ Order created successfully: $order_number (ID: $order_id)");
    header('Location: ../../public/order-success.php?order=' . $order_number);
    exit;
    
} catch (Exception $e) {
    error_log("ERROR: Order creation failed - " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
    
    if (isset($conn)) {
        $conn->rollBack();
    }
    $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
    header('Location: ../../public/checkout.php');
    exit;
}
