<?php
/**
 * API: Submit Customer Review
 * يسمح للعملاء بإضافة آرائهم (تحتاج موافقة الأدمن)
 */

session_start();
header('Content-Type: application/json');

require_once '../../config/database.php';

try {
    // Get form data
    $product_id = (int)($_POST['product_id'] ?? 0);
    $rating = (int)($_POST['rating'] ?? 0);
    $comment = trim($_POST['comment'] ?? '');
    $user_id = $_SESSION['user_id'] ?? null;
    
    // Validation
    if (!$user_id) {
        echo json_encode([
            'success' => false,
            'message' => 'يجب تسجيل الدخول أولاً'
        ]);
        exit;
    }
    
    if ($product_id <= 0) {
        echo json_encode([
            'success' => false,
            'message' => 'معرف المنتج غير صحيح'
        ]);
        exit;
    }
    
    if (empty($comment)) {
        echo json_encode([
            'success' => false,
            'message' => 'الرجاء إدخال تعليقك'
        ]);
        exit;
    }
    
    if ($rating < 1 || $rating > 5) {
        echo json_encode([
            'success' => false,
            'message' => 'الرجاء اختيار تقييم من 1 إلى 5 نجوم'
        ]);
        exit;
    }
    
    if (strlen($comment) < 10) {
        echo json_encode([
            'success' => false,
            'message' => 'التعليق يجب أن يكون 10 أحرف على الأقل'
        ]);
        exit;
    }
    
    $database = new Database();
    $conn = $database->getConnection();
    
    // Check if reviews table exists, if not create it
    $check_table = "SHOW TABLES LIKE 'reviews'";
    $result = $conn->query($check_table);
    
    if ($result->rowCount() == 0) {
        // Create reviews table
        $create_table = "CREATE TABLE IF NOT EXISTS reviews (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            product_id INT NOT NULL,
            rating INT NOT NULL CHECK (rating >= 1 AND rating <= 5),
            comment TEXT NOT NULL,
            status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_product (product_id),
            INDEX idx_user (user_id),
            INDEX idx_status (status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        $conn->exec($create_table);
    } else {
        // Check if status column exists, if not add it
        try {
            $check_col = "SHOW COLUMNS FROM reviews LIKE 'status'";
            $col_result = $conn->query($check_col);
            if ($col_result->rowCount() == 0) {
                $conn->exec("ALTER TABLE reviews ADD COLUMN status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending' AFTER comment");
            }
        } catch (PDOException $e) {
            // Column might already exist
        }
    }
    
    // Check if user already reviewed this product
    $check_query = "SELECT id FROM reviews WHERE user_id = :user_id AND product_id = :product_id";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bindParam(':user_id', $user_id);
    $check_stmt->bindParam(':product_id', $product_id);
    $check_stmt->execute();
    
    if ($check_stmt->rowCount() > 0) {
        echo json_encode([
            'success' => false,
            'message' => 'لقد قمت بتقييم هذا المنتج من قبل'
        ]);
        exit;
    }
    
    // Insert review
    $query = "INSERT INTO reviews (user_id, product_id, rating, comment, status, created_at) 
              VALUES (:user_id, :product_id, :rating, :comment, 'approved', NOW())";
    
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':product_id', $product_id);
    $stmt->bindParam(':rating', $rating);
    $stmt->bindParam(':comment', $comment);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'شكراً لك! تم إرسال رأيك بنجاح. سيظهر بعد المراجعة.'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'حدث خطأ، حاول مرة أخرى'
        ]);
    }
    
} catch (PDOException $e) {
    // Log the error for debugging
    error_log("Review submission error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ في النظام: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    error_log("Review submission error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ في النظام'
    ]);
}
