<?php
/**
 * Setup: Create Reviews System
 * إنشاء نظام التقييمات الكامل
 */

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

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    echo "🚀 بدء إنشاء نظام التقييمات.../n/n";
    
    // 1. Create reviews table
    echo "📋 إنشاء جدول التقييمات.../n";
    $create_reviews = "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),
        INDEX idx_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    $conn->exec($create_reviews);
    echo "✅ تم إنشاء جدول التقييمات/n/n";
    
    // 2. Check if old reviews table exists and migrate data
    echo "🔄 التحقق من البيانات القديمة.../n";
    $check_old = "SHOW COLUMNS FROM reviews";
    $result = $conn->query($check_old);
    $columns = [];
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $columns[] = $row['Field'];
    }
    
    // If old structure exists (with is_approved), migrate to new structure
    if (in_array('is_approved', $columns) && !in_array('status', $columns)) {
        echo "📦 ترحيل البيانات من النظام القديم.../n";
        $conn->exec("ALTER TABLE reviews ADD COLUMN status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending' AFTER comment");
        $conn->exec("UPDATE reviews SET status = CASE WHEN is_approved = 1 THEN 'approved' ELSE 'pending' END");
        echo "✅ تم ترحيل البيانات/n/n";
    }
    
    // 3. Add some sample reviews for testing
    echo "📝 إضافة تقييمات تجريبية.../n";
    
    // Get first product and user
    $product = $conn->query("SELECT id FROM products LIMIT 1")->fetch();
    $user = $conn->query("SELECT id FROM users LIMIT 1")->fetch();
    
    if ($product && $user) {
        $sample_reviews = [
            [
                'rating' => 5,
                'comment' => 'منتج رائع جداً! جودة ممتازة وسعر مناسب. أنصح بشدة بالشراء.'
            ],
            [
                'rating' => 4,
                'comment' => 'منتج جيد بشكل عام، لكن التوصيل استغرق وقتاً أطول من المتوقع.'
            ],
            [
                'rating' => 5,
                'comment' => 'تجربة رائعة! المنتج كما في الوصف تماماً والتغليف ممتاز.'
            ]
        ];
        
        $insert_review = $conn->prepare("
            INSERT INTO reviews (user_id, product_id, rating, comment, status, created_at)
            VALUES (:user_id, :product_id, :rating, :comment, 'approved', NOW())
        ");
        
        foreach ($sample_reviews as $review) {
            try {
                $insert_review->execute([
                    ':user_id' => $user['id'],
                    ':product_id' => $product['id'],
                    ':rating' => $review['rating'],
                    ':comment' => $review['comment']
                ]);
            } catch (PDOException $e) {
                // Review might already exist
            }
        }
        
        echo "✅ تم إضافة التقييمات التجريبية/n/n";
    }
    
    // 4. Create admin page for managing reviews
    echo "🎨 إنشاء صفحة إدارة التقييمات.../n";
    
    $admin_page = <<<'PHP'
<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

$database = new Database();
$db = $database->getConnection();

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['review_id'], $_POST['status'])) {
    $review_id = (int)$_POST['review_id'];
    $status = $_POST['status'];
    
    if (in_array($status, ['pending', 'approved', 'rejected'])) {
        $stmt = $db->prepare("UPDATE reviews SET status = ? WHERE id = ?");
        $stmt->execute([$status, $review_id]);
        $success_message = "تم تحديث حالة التقييم";
    }
}

// Get all reviews
$stmt = $db->prepare("
    SELECT r.*, u.name as user_name, p.name as product_name
    FROM reviews r
    LEFT JOIN users u ON r.user_id = u.id
    LEFT JOIN products p ON r.product_id = p.id
    ORDER BY r.created_at DESC
");
$stmt->execute();
$reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stats = $db->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
        AVG(rating) as avg_rating
    FROM reviews
")->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة التقييمات</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Tajawal', sans-serif; background: #F3F4F6; }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        .header { background: white; padding: 20px; border-radius: 12px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 20px; }
        .stat-card { background: white; padding: 20px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .stat-value { font-size: 32px; font-weight: 700; color: #E57393; }
        .stat-label { color: #6B7280; margin-top: 8px; }
        .reviews-list { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .review-item { padding: 20px; border-bottom: 1px solid #E5E7EB; }
        .review-item:last-child { border-bottom: none; }
        .review-header { display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px; }
        .review-info { flex: 1; }
        .review-user { font-weight: 600; color: #111827; }
        .review-product { color: #6B7280; font-size: 14px; }
        .review-rating { color: #F59E0B; font-size: 18px; }
        .review-comment { color: #374151; line-height: 1.6; margin-bottom: 12px; }
        .review-meta { display: flex; gap: 16px; font-size: 13px; color: #9CA3AF; }
        .status-badge { padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-pending { background: #FEF3C7; color: #92400E; }
        .status-approved { background: #D1FAE5; color: #065F46; }
        .status-rejected { background: #FEE2E2; color: #991B1B; }
        .action-buttons { display: flex; gap: 8px; }
        .btn { padding: 8px 16px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 13px; }
        .btn-approve { background: #10B981; color: white; }
        .btn-reject { background: #EF4444; color: white; }
        .btn-pending { background: #F59E0B; color: white; }
        .success-message { background: #D1FAE5; color: #065F46; padding: 12px 20px; border-radius: 8px; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-star"></i> إدارة التقييمات</h1>
        </div>
        
        <?php if (isset($success_message)): ?>
            <div class="success-message"><?php echo $success_message; ?></div>
        <?php endif; ?>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-value"><?php echo $stats['total']; ?></div>
                <div class="stat-label">إجمالي التقييمات</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $stats['pending']; ?></div>
                <div class="stat-label">قيد المراجعة</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $stats['approved']; ?></div>
                <div class="stat-label">معتمدة</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo number_format($stats['avg_rating'], 1); ?> ⭐</div>
                <div class="stat-label">متوسط التقييم</div>
            </div>
        </div>
        
        <div class="reviews-list">
            <h2 style="margin-bottom: 20px;">جميع التقييمات</h2>
            
            <?php foreach ($reviews as $review): ?>
                <div class="review-item">
                    <div class="review-header">
                        <div class="review-info">
                            <div class="review-user"><?php echo htmlspecialchars($review['user_name'] ?? 'عميل'); ?></div>
                            <div class="review-product">على: <?php echo htmlspecialchars($review['product_name']); ?></div>
                            <div class="review-rating">
                                <?php for ($i = 1; $i <= 5; $i++) echo $i <= $review['rating'] ? '⭐' : '☆'; ?>
                            </div>
                        </div>
                        <span class="status-badge status-<?php echo $review['status']; ?>">
                            <?php 
                            echo $review['status'] === 'pending' ? 'قيد المراجعة' : 
                                ($review['status'] === 'approved' ? 'معتمد' : 'مرفوض'); 
                            ?>
                        </span>
                    </div>
                    
                    <div class="review-comment"><?php echo nl2br(htmlspecialchars($review['comment'])); ?></div>
                    
                    <div class="review-meta">
                        <span><i class="far fa-clock"></i> <?php echo date('d/m/Y H:i', strtotime($review['created_at'])); ?></span>
                    </div>
                    
                    <div class="action-buttons" style="margin-top: 12px;">
                        <?php if ($review['status'] !== 'approved'): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                <input type="hidden" name="status" value="approved">
                                <button type="submit" class="btn btn-approve">
                                    <i class="fas fa-check"></i> اعتماد
                                </button>
                            </form>
                        <?php endif; ?>
                        
                        <?php if ($review['status'] !== 'rejected'): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                <input type="hidden" name="status" value="rejected">
                                <button type="submit" class="btn btn-reject">
                                    <i class="fas fa-times"></i> رفض
                                </button>
                            </form>
                        <?php endif; ?>
                        
                        <?php if ($review['status'] !== 'pending'): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="review_id" value="<?php echo $review['id']; ?>">
                                <input type="hidden" name="status" value="pending">
                                <button type="submit" class="btn btn-pending">
                                    <i class="fas fa-clock"></i> قيد المراجعة
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
            
            <?php if (empty($reviews)): ?>
                <div style="text-align: center; padding: 40px; color: #9CA3AF;">
                    <i class="fas fa-star" style="font-size: 48px; margin-bottom: 16px;"></i>
                    <p>لا توجد تقييمات بعد</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
PHP;
    
    file_put_contents('../admin/reviews.php', $admin_page);
    echo "✅ تم إنشاء صفحة إدارة التقييمات/n/n";
    
    echo "✨ تم إنشاء نظام التقييمات بنجاح!/n/n";
    echo "📍 يمكنك الآن:/n";
    echo "   - عرض التقييمات في صفحة المنتج/n";
    echo "   - إضافة تقييمات جديدة (للمستخدمين المسجلين)/n";
    echo "   - إدارة التقييمات من: admin/reviews.php/n/n";
    
} catch (PDOException $e) {
    echo "❌ خطأ: " . $e->getMessage() . "/n";
}
