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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$database = new Database();
$conn = $database->getConnection();
$id = $_GET['id'] ?? 0;

try {
    $stmt = $conn->prepare("SELECT * FROM consultations WHERE id = ?");
    $stmt->execute([$id]);
    $consultation = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$consultation) {
        header('Location: index.php');
        exit;
    }
} catch (PDOException $e) {
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $duration = $_POST['duration'] ?? 0;
    $price = $_POST['price'] ?? 0;
    $discount_price = $_POST['discount_price'] ?? null;
    $consultant_name = $_POST['consultant_name'] ?? '';
    $consultant_title = $_POST['consultant_title'] ?? '';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    $features = [];
    if (!empty($_POST['features'])) {
        $features = array_filter(array_map('trim', explode("\n", $_POST['features'])));
    }
    $features_json = json_encode($features, JSON_UNESCAPED_UNICODE);
    
    $image_path = $consultation['image'];
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../../uploads/consultations/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
        
        if ($image_path && file_exists('../../' . $image_path)) {
            unlink('../../' . $image_path);
        }
        
        $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $new_filename = 'consultation_' . time() . '_' . uniqid() . '.' . $file_extension;
        $upload_path = $upload_dir . $new_filename;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
            $image_path = 'uploads/consultations/' . $new_filename;
        }
    }
    
    try {
        $stmt = $conn->prepare("
            UPDATE consultations 
            SET title = ?, description = ?, image = ?, duration = ?, price = ?, 
                discount_price = ?, consultant_name = ?, consultant_title = ?, 
                features = ?, is_active = ?
            WHERE id = ?
        ");
        
        $stmt->execute([
            $title, $description, $image_path, $duration, $price, 
            $discount_price, $consultant_name, $consultant_title, 
            $features_json, $is_active, $id
        ]);
        
        header('Location: index.php?updated=1');
        exit;
    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
}

$features_text = '';
if ($consultation['features']) {
    $features_array = json_decode($consultation['features'], true);
    if (is_array($features_array)) {
        $features_text = implode("\n", $features_array);
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>تعديل استشارة - Roz Skin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin-layout.css">
<link rel="stylesheet" href="../assets/css/admin-improvements.css">
<style>
body { font-family: 'Tajawal', sans-serif; }
</style>
</head>
<body class="bg-gray-50 min-h-screen">

<?php include '../includes/sidebar.php'; ?>

<div style="margin-right: 280px; padding: 24px;">
    
    <header class="bg-white shadow-sm border-b border-gray-200 rounded-lg mb-6 p-6">
        <div class="flex items-center gap-4">
            <a href="index.php" class="text-gray-600 hover:text-gray-900">
                <i class="fas fa-arrow-right text-xl"></i>
            </a>
            <div>
                <h1 class="text-3xl font-bold text-gray-900">✏️ تعديل استشارة</h1>
                <p class="text-sm text-gray-500 mt-1">تعديل بيانات الاستشارة</p>
            </div>
        </div>
    </header>

    <?php if (isset($error)): ?>
        <div class="bg-red-50 border-r-4 border-red-400 p-4 rounded-lg mb-6">
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle text-red-400 text-xl ml-3"></i>
                <p class="text-sm text-red-700">❌ <?php echo htmlspecialchars($error); ?></p>
            </div>
        </div>
    <?php endif; ?>

    <div class="bg-white rounded-lg shadow p-8 max-w-4xl mx-auto">
        <form method="POST" enctype="multipart/form-data">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-bold text-gray-700 mb-2">عنوان الاستشارة *</label>
                    <input type="text" name="title" value="<?php echo htmlspecialchars($consultation['title']); ?>" required
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-bold text-gray-700 mb-2">الوصف</label>
                    <textarea name="description" rows="4"
                              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent"><?php echo htmlspecialchars($consultation['description']); ?></textarea>
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-bold text-gray-700 mb-2">صورة الاستشارة</label>
                    <?php if ($consultation['image']): ?>
                        <img src="../../<?php echo htmlspecialchars($consultation['image']); ?>" class="w-48 h-32 object-cover rounded-lg mb-3" alt="Current">
                        <p class="text-sm text-gray-500 mb-2">اختر صورة جديدة لتغيير الصورة الحالية</p>
                    <?php endif; ?>
                    <input type="file" name="image" accept="image/*"
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">المدة (بالدقائق) *</label>
                    <input type="number" name="duration" value="<?php echo $consultation['duration']; ?>" required min="1"
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">السعر الأصلي (ج.م) *</label>
                    <input type="number" name="price" value="<?php echo $consultation['price']; ?>" required min="0" step="0.01"
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-bold text-gray-700 mb-2">السعر بعد الخصم (ج.م)</label>
                    <input type="number" name="discount_price" value="<?php echo $consultation['discount_price']; ?>" min="0" step="0.01"
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اسم المستشار</label>
                    <input type="text" name="consultant_name" value="<?php echo htmlspecialchars($consultation['consultant_name']); ?>"
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">لقب المستشار</label>
                    <input type="text" name="consultant_title" value="<?php echo htmlspecialchars($consultation['consultant_title']); ?>"
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent">
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-bold text-gray-700 mb-2">مميزات الاستشارة (كل ميزة في سطر)</label>
                    <textarea name="features" rows="4" placeholder="مثال:&#10;تحليل شامل للبشرة&#10;توصيات مخصصة&#10;متابعة لمدة شهر"
                              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent"><?php echo htmlspecialchars($features_text); ?></textarea>
                </div>
                
                <div class="md:col-span-2">
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" name="is_active" <?php echo $consultation['is_active'] ? 'checked' : ''; ?> class="w-5 h-5 text-pink-600 rounded focus:ring-pink-500">
                        <span class="text-sm font-bold text-gray-700">نشط</span>
                    </label>
                </div>
            </div>
            
            <div class="flex gap-4 mt-8">
                <button type="submit" class="flex-1 bg-gradient-to-r from-pink-500 to-pink-600 text-white py-3 rounded-lg hover:from-pink-600 hover:to-pink-700 transition font-bold">
                    <i class="fas fa-save mr-2"></i>حفظ التعديلات
                </button>
                <a href="index.php" class="px-8 py-3 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition font-bold">
                    إلغاء
                </a>
            </div>
        </form>
    </div>
</div>

</body>
</html>
