<?php
/**
 * اختبار حفظ التعديلات - تشخيص المشكلة
 */

session_start();

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die('يجب تسجيل الدخول كأدمن');
}

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

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

echo "<!DOCTYPE html>
<html lang='ar' dir='rtl'>
<head>
    <meta charset='UTF-8'>
    <title>اختبار حفظ التعديلات</title>
    <style>
        body { font-family: Arial; padding: 20px; background: #f5f5f5; }
        .box { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .success { background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; border-right: 4px solid #28a745; }
        .error { background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; border-right: 4px solid #dc3545; }
        .info { background: #d1ecf1; color: #0c5460; padding: 15px; border-radius: 5px; border-right: 4px solid #17a2b8; }
        pre { background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto; }
        button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>";

echo "<h1>🔍 اختبار حفظ تعديلات المنتج</h1>";

// Test 1: Check if POST works
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_update'])) {
    echo "<div class='box'>";
    echo "<h2>✅ POST Request يعمل بنجاح!</h2>";
    echo "<div class='success'>تم استقبال البيانات من الفورم</div>";
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
    echo "</div>";
    
    // Test 2: Try to update a product
    $product_id = $_POST['product_id'] ?? null;
    $new_name = $_POST['new_name'] ?? null;
    
    if ($product_id && $new_name) {
        try {
            // Get current product
            $query = "SELECT * FROM products WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$product_id]);
            $product = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($product) {
                echo "<div class='box'>";
                echo "<h3>📦 المنتج قبل التحديث:</h3>";
                echo "<pre>";
                echo "ID: " . $product['id'] . "/n";
                echo "الاسم: " . $product['name'] . "/n";
                echo "السعر: " . $product['price'] . "/n";
                echo "</pre>";
                
                // Update product
                $query = "UPDATE products SET name = ?, updated_at = NOW() WHERE id = ?";
                $stmt = $db->prepare($query);
                $result = $stmt->execute([$new_name, $product_id]);
                
                if ($result) {
                    echo "<div class='success'>✅ تم التحديث بنجاح!</div>";
                    
                    // Get updated product
                    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
                    $stmt->execute([$product_id]);
                    $updated_product = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    echo "<h3>📦 المنتج بعد التحديث:</h3>";
                    echo "<pre>";
                    echo "ID: " . $updated_product['id'] . "/n";
                    echo "الاسم: " . $updated_product['name'] . "/n";
                    echo "السعر: " . $updated_product['price'] . "/n";
                    echo "آخر تحديث: " . $updated_product['updated_at'] . "/n";
                    echo "</pre>";
                } else {
                    echo "<div class='error'>❌ فشل التحديث!</div>";
                }
                echo "</div>";
            } else {
                echo "<div class='error'>❌ المنتج غير موجود!</div>";
            }
            
        } catch (Exception $e) {
            echo "<div class='error'>";
            echo "<h3>❌ خطأ في قاعدة البيانات:</h3>";
            echo "<p>" . $e->getMessage() . "</p>";
            echo "</div>";
        }
    }
} else {
    // Show test form
    echo "<div class='box'>";
    echo "<h2>📝 نموذج الاختبار</h2>";
    echo "<div class='info'>اختر منتج وغيّر اسمه لاختبار الحفظ</div>";
    
    // Get first product
    try {
        $query = "SELECT id, name, price FROM products LIMIT 5";
        $stmt = $db->prepare($query);
        $stmt->execute();
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (!empty($products)) {
            echo "<form method='POST'>";
            echo "<div style='margin: 15px 0;'>";
            echo "<label style='display: block; margin-bottom: 5px; font-weight: bold;'>اختر منتج:</label>";
            echo "<select name='product_id' style='padding: 8px; width: 100%; max-width: 400px;' required>";
            foreach ($products as $p) {
                echo "<option value='{$p['id']}'>{$p['name']} (السعر: {$p['price']} ج.م)</option>";
            }
            echo "</select>";
            echo "</div>";
            
            echo "<div style='margin: 15px 0;'>";
            echo "<label style='display: block; margin-bottom: 5px; font-weight: bold;'>الاسم الجديد:</label>";
            echo "<input type='text' name='new_name' value='اسم تجريبي - " . date('H:i:s') . "' style='padding: 8px; width: 100%; max-width: 400px;' required>";
            echo "</div>";
            
            echo "<button type='submit' name='test_update'>🧪 اختبار التحديث</button>";
            echo "</form>";
        } else {
            echo "<div class='error'>❌ لا توجد منتجات في قاعدة البيانات!</div>";
        }
        
    } catch (Exception $e) {
        echo "<div class='error'>❌ خطأ: " . $e->getMessage() . "</div>";
    }
    echo "</div>";
}

// Show current products
echo "<div class='box'>";
echo "<h2>📋 المنتجات الحالية</h2>";
try {
    $query = "SELECT id, name, price, updated_at FROM products ORDER BY updated_at DESC LIMIT 5";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($products)) {
        echo "<table style='width: 100%; border-collapse: collapse;'>";
        echo "<tr style='background: #f8f9fa;'>";
        echo "<th style='padding: 10px; text-align: right; border: 1px solid #dee2e6;'>ID</th>";
        echo "<th style='padding: 10px; text-align: right; border: 1px solid #dee2e6;'>الاسم</th>";
        echo "<th style='padding: 10px; text-align: right; border: 1px solid #dee2e6;'>السعر</th>";
        echo "<th style='padding: 10px; text-align: right; border: 1px solid #dee2e6;'>آخر تحديث</th>";
        echo "</tr>";
        
        foreach ($products as $p) {
            echo "<tr>";
            echo "<td style='padding: 10px; border: 1px solid #dee2e6;'>{$p['id']}</td>";
            echo "<td style='padding: 10px; border: 1px solid #dee2e6;'>{$p['name']}</td>";
            echo "<td style='padding: 10px; border: 1px solid #dee2e6;'>{$p['price']} ج.م</td>";
            echo "<td style='padding: 10px; border: 1px solid #dee2e6;'>{$p['updated_at']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
} catch (Exception $e) {
    echo "<div class='error'>❌ خطأ: " . $e->getMessage() . "</div>";
}
echo "</div>";

echo "<div class='box'>";
echo "<h2>🔗 روابط مفيدة</h2>";
echo "<p><a href='index.php' style='color: #007bff;'>← العودة لقائمة المنتجات</a></p>";
echo "<p><a href='edit.php?id=1' style='color: #007bff;'>← تعديل المنتج #1</a></p>";
echo "</div>";

echo "</body></html>";
?>
