<?php
// ========================================
// مدیریت نظرات (نسخه کاملاً اصلاح‌شده و ایمن)
// پروژه فروشگاه کیف‌لند
// ========================================
ini_set('display_errors', 0); // جلوگیری از نمایش هشدارها در محیط زنده
error_reporting(E_ALL);

require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!class_exists('Auth') || !method_exists('Auth', 'requireAdmin')) die('خطای سیستم احراز هویت');
Auth::requireAdmin();

$db = Database::getInstance()->getConnection();
$pageTitle = 'مدیریت نظرات | کیف‌لند';

$success = '';
$error = '';
$table_exists = false;
$status_col_exists = false;

// بررسی وجود جدول و ستون status
try {
    $check_tbl = $db->query("SHOW TABLES LIKE 'reviews'");
    if ($check_tbl->rowCount() > 0) {
        $table_exists = true;
        $check_col = $db->query("SHOW COLUMNS FROM reviews LIKE 'status'");
        if ($check_col->rowCount() > 0) $status_col_exists = true;
    }
} catch (Exception $e) { $error = 'خطا در بررسی ساختار دیتابیس.'; }

// ========================================
// پردازش POST
// ========================================
if ($table_exists && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action']) && isset($_POST['review_id'])) {
            $id = (int)$_POST['review_id'];
            $action = $_POST['action'];
            
            if ($action === 'update_status' && isset($_POST['status']) && $status_col_exists) {
                $status = in_array($_POST['status'], ['pending', 'approved', 'rejected']) ? $_POST['status'] : 'pending';
                // هم status هم is_approved رو آپدیت می‌کنیم تا فرانت‌اند نمایش بده
                $is_approved = ($status === 'approved') ? 1 : 0;
                $db->prepare("UPDATE reviews SET status = ?, is_approved = ?, updated_at = NOW() WHERE id = ?")
                   ->execute([$status, $is_approved, $id]);
                // آپدیت میانگین امتیاز محصول
                $stmt_prod = $db->prepare("SELECT product_id FROM reviews WHERE id = ?");
                $stmt_prod->execute([$id]);
                $rev_row = $stmt_prod->fetch();
                if ($rev_row) {
                    $db->prepare("UPDATE products SET 
                        rating_avg = (SELECT COALESCE(AVG(rating),0) FROM reviews WHERE product_id = ? AND is_approved = 1),
                        rating_count = (SELECT COUNT(*) FROM reviews WHERE product_id = ? AND is_approved = 1)
                        WHERE id = ?")->execute([$rev_row['product_id'], $rev_row['product_id'], $rev_row['product_id']]);
                }
                $success = 'وضعیت نظر بروزرسانی شد.';
            } elseif ($action === 'delete') {
                $db->prepare("DELETE FROM reviews WHERE id = ?")->execute([$id]);
                $success = 'نظر حذف شد.';
            }
        } 
        elseif (isset($_POST['bulk_action']) && !empty($_POST['review_ids']) && $status_col_exists) {
            $ids = array_filter($_POST['review_ids'], 'is_numeric');
            if (!empty($ids)) {
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $bulk = $_POST['bulk_action'];
                if ($bulk === 'approve') {
                    $db->prepare("UPDATE reviews SET status = 'approved', is_approved = 1, updated_at = NOW() WHERE id IN ($placeholders)")->execute($ids);
                    // آپدیت امتیاز محصولات مربوطه
                    $stmt_pids = $db->prepare("SELECT DISTINCT product_id FROM reviews WHERE id IN ($placeholders)");
                    $stmt_pids->execute($ids);
                    foreach ($stmt_pids->fetchAll() as $prow) {
                        $db->prepare("UPDATE products SET rating_avg=(SELECT COALESCE(AVG(rating),0) FROM reviews WHERE product_id=? AND is_approved=1), rating_count=(SELECT COUNT(*) FROM reviews WHERE product_id=? AND is_approved=1) WHERE id=?")->execute([$prow['product_id'],$prow['product_id'],$prow['product_id']]);
                    }
                } elseif ($bulk === 'reject') {
                    $db->prepare("UPDATE reviews SET status = 'rejected', is_approved = 0, updated_at = NOW() WHERE id IN ($placeholders)")->execute($ids);
                } elseif ($bulk === 'delete') {
                    $db->prepare("DELETE FROM reviews WHERE id IN ($placeholders)")->execute($ids);
                }
                $success = 'عملیات دسته‌جمعی با موفقیت انجام شد.';
            }
        }
    } catch (Exception $e) { $error = 'خطا در پردازش: ' . $e->getMessage(); }
}

// ========================================
// دریافت داده‌ها
// ========================================
$reviews = [];
$status_filter = $_GET['status'] ?? 'all';
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 12;
$offset = ($page - 1) * $per_page;
$stats = ['all' => 0, 'pending' => 0, 'approved' => 0, 'rejected' => 0];

if ($table_exists) {
    try {
        // ساخت کوئری انتخابی امن
        $select_cols = 'r.id, r.product_id, r.user_id, r.rating, r.comment, r.created_at';
        if ($status_col_exists) $select_cols .= ', r.status';
        
        $sql = "SELECT $select_cols, p.name as product_name, u.full_name as user_name, u.email as user_email 
                FROM reviews r 
                LEFT JOIN products p ON r.product_id = p.id 
                LEFT JOIN users u ON r.user_id = u.id 
                WHERE 1=1";
        $params = [];

        if ($status_col_exists && $status_filter != 'all') { $sql .= " AND r.status = ?"; $params[] = $status_filter; }
        if ($search !== '') {
            $sql .= " AND (r.comment LIKE ? OR u.full_name LIKE ? OR p.name LIKE ?)";
            $p = "%$search%"; array_push($params, $p, $p, $p);
        }

        // شمارش کل
        $count_sql = preg_replace('/SELECT .+ FROM/', 'SELECT COUNT(*) FROM', $sql);
        $stmt_count = $db->prepare($count_sql);
        $stmt_count->execute($params);
        $total_reviews = $stmt_count->fetchColumn();
        $stats['all'] = $total_reviews;
        $total_pages = ceil($total_reviews / $per_page);

        // دریافت لیست
        $sql .= " ORDER BY r.created_at DESC LIMIT ? OFFSET ?";
        array_push($params, (int)$per_page, (int)$offset);
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $reviews = $stmt->fetchAll();

        // آمار وضعیت‌ها (فقط اگر ستون وجود دارد)
        if ($status_col_exists) {
            $stmt = $db->query("SELECT status, COUNT(*) as c FROM reviews GROUP BY status");
            foreach ($stmt->fetchAll() as $row) {
                if (isset($stats[$row['status']])) $stats[$row['status']] = $row['c'];
            }
        } else {
            // اگر ستون نبود، همه را pending فرض کن
            $stats['pending'] = $total_reviews;
        }

    } catch (Exception $e) { $error = 'خطا در دریافت اطلاعات: ' . $e->getMessage(); }
}

// تابع تاریخ شمسی ایمن
function safe_jdate($timestamp) {
    return function_exists('jdate') ? jdate($timestamp) : date('Y/m/d H:i', strtotime($timestamp));
}

include 'includes/admin-header.php';
?>

<style>
.reviews-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-wrap:wrap; gap:16px; }
.stats-row { display:grid; grid-template-columns:repeat(4,1fr); gap:12px; margin-bottom:20px; }
.stat-box { background:var(--glass-bg); border:1px solid var(--glass-border); border-radius:var(--radius-sm); padding:14px; text-align:center; cursor:pointer; transition:0.2s; text-decoration:none; color:inherit; }
.stat-box:hover { background:var(--glass-bg-light); transform:translateY(-2px); }
.stat-box.active { border-color:var(--primary); background:var(--primary-light); }
.stat-box h4 { margin:0; font-size:22px; color:var(--primary); font-weight:700; }
.stat-box p { margin:4px 0 0; font-size:12px; color:var(--text-secondary); }
.filters-bar { display:flex; gap:10px; flex-wrap:wrap; margin-bottom:20px; background:var(--glass-bg); padding:12px; border-radius:var(--radius-sm); border:1px solid var(--glass-border); }
.filter-input { flex:1; min-width:140px; padding:9px 12px; border:1px solid var(--glass-border); border-radius:8px; background:var(--glass-bg-light); font-family:inherit; font-size:13px; color:var(--text-primary); }
.filter-input:focus { outline:none; border-color:var(--primary); box-shadow:0 0 0 3px rgba(0,122,255,0.15); }
.reviews-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(320px, 1fr)); gap:16px; margin-bottom:24px; }
.review-card { background:var(--glass-bg); border:1px solid var(--glass-border); border-radius:var(--radius); padding:16px; transition:0.2s; position:relative; }
.review-card:hover { background:var(--glass-bg-light); transform:translateY(-2px); box-shadow:var(--shadow-soft); }
.review-card input[type="checkbox"] { position:absolute; top:12px; left:12px; width:18px; height:18px; accent-color:var(--primary); }
.review-top { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:10px; padding-left:24px; }
.review-user { font-weight:600; font-size:14px; }
.review-email { font-size:11px; color:var(--text-muted); }
.review-product { font-size:12px; color:var(--primary); text-decoration:none; margin-top:2px; display:block; }
.stars { color:#FFC107; font-size:13px; margin:6px 0; letter-spacing:1px; }
.review-text { font-size:13px; line-height:1.6; color:var(--text-primary); margin-bottom:12px; white-space:pre-wrap; }
.review-meta { display:flex; justify-content:space-between; align-items:center; font-size:11px; color:var(--text-muted); border-top:1px solid rgba(255,255,255,0.15); padding-top:10px; }
.status-badge { padding:3px 8px; border-radius:12px; font-weight:600; font-size:10px; }
.status-pending { background:#fff3cd; color:#856404; }
.status-approved { background:#d4edda; color:#155724; }
.status-rejected { background:#f8d7da; color:#721c24; }
.review-actions { display:flex; gap:6px; margin-top:10px; }
.btn-xs { padding:5px 8px; font-size:11px; border-radius:6px; border:none; cursor:pointer; font-family:inherit; }
.btn-approve { background:var(--success); color:#fff; }
.btn-reject { background:var(--warning); color:#fff; }
.btn-delete { background:var(--danger); color:#fff; }
.btn-outline { background:transparent; border:1px solid var(--glass-border); color:var(--text-primary); padding:8px 14px; border-radius:8px; cursor:pointer; font-family:inherit; }
.bulk-actions { display:flex; gap:8px; align-items:center; margin-bottom:16px; flex-wrap:wrap; }
.bulk-actions select { padding:8px; border-radius:8px; border:1px solid var(--glass-border); background:var(--glass-bg); font-family:inherit; }
.btn-primary { background:var(--primary); color:#fff; padding:8px 14px; border-radius:8px; border:none; cursor:pointer; font-family:inherit; }
.empty-state { text-align:center; padding:40px 20px; color:var(--text-muted); grid-column:1/-1; }
.empty-state i { font-size:48px; opacity:0.3; margin-bottom:12px; display:block; }
@media (max-width:768px) { .stats-row { grid-template-columns:repeat(2,1fr); } .reviews-grid { grid-template-columns:1fr; } .filters-bar { flex-direction:column; } }
</style>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div class="search-box"><i class="fas fa-search"></i><input type="text" placeholder="جستجو..."></div>
    </header>

    <div class="dashboard-content">
        <div class="reviews-header">
            <div class="page-title" style="margin:0;"><h1>مدیریت نظرات</h1><p>بررسی و مدیریت بازخورد کاربران</p></div>
        </div>

        <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>

        <?php if (!$table_exists): ?>
        <div class="glass-card" style="text-align:center; padding:30px;">
            <h3 style="color:var(--danger);">جدول نظرات یافت نشد</h3>
            <p>لطفاً وارد phpMyAdmin شوید و کوئری زیر را اجرا کنید:</p>
            <code style="display:block; background:#f4f4f4; padding:10px; margin:10px 0; text-align:left; direction:ltr; border-radius:6px; font-size:12px;">
            CREATE TABLE IF NOT EXISTS `reviews` ( `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, `product_id` INT UNSIGNED NOT NULL, `user_id` INT UNSIGNED DEFAULT NULL, `rating` TINYINT NOT NULL DEFAULT 5, `comment` TEXT, `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            </code>
        </div>
        <?php elseif (!$status_col_exists): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-triangle"></i> ستون <code>status</code> در جدول <code>reviews</code> وجود ندارد.
            <br>لطفاً این دستور را در phpMyAdmin اجرا کنید:
            <code style="display:block; background:rgba(0,0,0,0.05); padding:8px; margin-top:8px; border-radius:4px; font-family:monospace;">
            ALTER TABLE `reviews` ADD COLUMN `status` ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending' AFTER `comment`;
            </code>
        </div>
        <?php else: ?>

        <div class="stats-row">
            <a href="?status=all" class="stat-box <?= $status_filter=='all'?'active':'' ?>"><h4><?= $stats['all'] ?></h4><p>کل نظرات</p></a>
            <a href="?status=pending" class="stat-box <?= $status_filter=='pending'?'active':'' ?>"><h4><?= $stats['pending'] ?></h4><p>در انتظار</p></a>
            <a href="?status=approved" class="stat-box <?= $status_filter=='approved'?'active':'' ?>"><h4><?= $stats['approved'] ?></h4><p>تایید شده</p></a>
            <a href="?status=rejected" class="stat-box <?= $status_filter=='rejected'?'active':'' ?>"><h4><?= $stats['rejected'] ?></h4><p>رد شده</p></a>
        </div>

        <form method="GET" class="filters-bar">
            <input type="hidden" name="status" value="<?= $status_filter ?>">
            <input type="text" name="search" class="filter-input" placeholder="جستجو در متن، کاربر یا محصول..." value="<?= htmlspecialchars($search) ?>">
            <button type="submit" class="btn-primary">جستجو</button>
            <?php if ($search): ?><a href="?status=<?= $status_filter ?>" class="btn-outline">پاک کردن</a><?php endif; ?>
        </form>

        <form method="POST" class="bulk-actions">
            <label style="font-size:13px;"><input type="checkbox" id="selectAll"> انتخاب همه</label>
            <select name="bulk_action">
                <option value="">عملیات دسته‌جمعی...</option>
                <option value="approve">تایید انتخاب‌ها</option>
                <option value="reject">رد انتخاب‌ها</option>
                <option value="delete">حذف انتخاب‌ها</option>
            </select>
            <button type="submit" class="btn-primary" onclick="return confirm('آیا مطمئن هستید؟')">اجرا</button>
        </form>

        <div class="reviews-grid">
            <?php foreach ($reviews as $rev): 
                // ✅ رفع خطای Undefined array key با مقدار پیش‌فرض
                $rev_status = $rev['status'] ?? 'pending';
                $status_text = 'در انتظار';
                $status_class = 'pending';
                if ($rev_status == 'approved') { $status_text = 'تایید شده'; $status_class = 'approved'; }
                elseif ($rev_status == 'rejected') { $status_text = 'رد شده'; $status_class = 'rejected'; }
            ?>
            <div class="review-card">
                <input type="checkbox" name="review_ids[]" value="<?= $rev['id'] ?>">
                <div class="review-top">
                    <div>
                        <div class="review-user"><?= htmlspecialchars($rev['user_name'] ?: 'کاربر مهمان') ?></div>
                        <div class="review-email"><?= htmlspecialchars($rev['user_email'] ?? '-') ?></div>
                        <a href="product-edit.php?id=<?= $rev['product_id'] ?>" class="review-product"><?= htmlspecialchars($rev['product_name'] ?: 'محصول حذف شده') ?></a>
                    </div>
                    <span class="status-badge status-<?= $status_class ?>"><?= $status_text ?></span>
                </div>
                <div class="stars"><?= str_repeat('★', (int)$rev['rating']) . str_repeat('☆', 5 - (int)$rev['rating']) ?></div>
                <div class="review-text"><?= htmlspecialchars($rev['comment']) ?></div>
                <div class="review-meta">
                    <span><i class="far fa-clock"></i> <?= safe_jdate($rev['created_at']) ?></span>
                    <span>ID: #<?= $rev['id'] ?></span>
                </div>
                <div class="review-actions">
                    <?php if ($rev_status !== 'approved'): ?>
                    <form method="POST" style="display:inline"><input type="hidden" name="action" value="update_status"><input type="hidden" name="status" value="approved"><input type="hidden" name="review_id" value="<?= $rev['id'] ?>"><button type="submit" class="btn-xs btn-approve">تایید</button></form>
                    <?php endif; ?>
                    <?php if ($rev_status !== 'rejected'): ?>
                    <form method="POST" style="display:inline"><input type="hidden" name="action" value="update_status"><input type="hidden" name="status" value="rejected"><input type="hidden" name="review_id" value="<?= $rev['id'] ?>"><button type="submit" class="btn-xs btn-reject">رد</button></form>
                    <?php endif; ?>
                    <form method="POST" style="display:inline" onsubmit="return confirm('حذف دائمی شود؟')"><input type="hidden" name="action" value="delete"><input type="hidden" name="review_id" value="<?= $rev['id'] ?>"><button type="submit" class="btn-xs btn-delete">حذف</button></form>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($reviews)): ?>
            <div class="empty-state"><i class="fas fa-comment-slash"></i><p>هیچ نظری با این فیلترها یافت نشد.</p></div>
            <?php endif; ?>
        </div>

        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?><a href="?<?= http_build_query(array_merge($_GET, ['page'=>$page-1])) ?>" class="page-link"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
            <?php for ($i=1; $i<=$total_pages; $i++): ?>
                <?php if ($i==1 || $i==$total_pages || abs($page-$i)<=2): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$i])) ?>" class="page-link <?= $i==$page?'active':'' ?>"><?= $i ?></a>
                <?php elseif (abs($page-$i)==3): ?><span style="color:var(--text-muted); padding:0 4px;">...</span><?php endif; ?>
            <?php endfor; ?>
            <?php if ($page < $total_pages): ?><a href="?<?= http_build_query(array_merge($_GET, ['page'=>$page+1])) ?>" class="page-link"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div>
</main>

<script src="assets/js/script.js"></script>
<script>
document.getElementById('selectAll')?.addEventListener('change', function() {
    document.querySelectorAll('input[name="review_ids[]"]').forEach(cb => cb.checked = this.checked);
});
</script>

<?php include 'includes/admin-footer.php'; ?>