<?php
// Add/Edit Slider
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}
require_once '../src/config/db.php';
require_once '../src/includes/functions.php';
require_once 'includes/lang.php';

$slider = [
    'id' => '',
    'title' => '',
    'description' => '',
    'image_url' => '',
    'link_url' => '',
    'sort_order' => 0,
    'active' => 1
];
$pageTitle = $t['slider_add_btn'];

function slider_admin_image_src($imagePath) {
    if (!$imagePath) {
        return '';
    }

    if (preg_match('/^https?:\/\//i', $imagePath)) {
        return $imagePath;
    }

    if (strpos($imagePath, '/') === 0) {
        return $imagePath;
    }

    if (strpos($imagePath, 'assets/') === 0) {
        return '../public/' . $imagePath;
    }

    return $imagePath;
}

function handle_slider_upload($currentImage, $isRTL, $deleteOld = false) {
    if (!isset($_FILES['image_file']) || $_FILES['image_file']['error'] === UPLOAD_ERR_NO_FILE) {
        return $currentImage;
    }

    if ($_FILES['image_file']['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException($isRTL ? 'تعذر رفع الصورة.' : 'Image upload failed.');
    }

    $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $originalName = $_FILES['image_file']['name'];
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

    if (!in_array($extension, $allowedExtensions, true)) {
        throw new RuntimeException($isRTL ? 'نوع الصورة غير مدعوم.' : 'Unsupported image type.');
    }

    if ($_FILES['image_file']['size'] > 5 * 1024 * 1024) {
        throw new RuntimeException($isRTL ? 'حجم الصورة يجب ألا يتجاوز 5MB.' : 'Image size must not exceed 5MB.');
    }

    $imageInfo = getimagesize($_FILES['image_file']['tmp_name']);
    if ($imageInfo === false) {
        throw new RuntimeException($isRTL ? 'الملف المرفوع ليس صورة صالحة.' : 'Uploaded file is not a valid image.');
    }

    $uploadDir = dirname(__DIR__) . '/public/assets/img/sliders';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0775, true);
    }

    $fileName = 'slider-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
    $targetPath = $uploadDir . '/' . $fileName;

    if (!move_uploaded_file($_FILES['image_file']['tmp_name'], $targetPath)) {
        throw new RuntimeException($isRTL ? 'تعذر حفظ الصورة.' : 'Could not save the image.');
    }

    // Delete the old image if requested and it exists
    if ($deleteOld && $currentImage) {
        $oldImagePath = dirname(__DIR__) . '/public/' . $currentImage;
        if (file_exists($oldImagePath)) {
            @unlink($oldImagePath);
        }
    }

    return 'assets/img/sliders/' . $fileName;
}

// Load existing slider if editing
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $pdo->prepare('SELECT * FROM sliders WHERE id = ?');
    $stmt->execute([$id]);
    $slider = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$slider) {
        header('Location: sliders.php');
        exit;
    }
    $pageTitle = $isRTL ? 'تعديل السلايدر' : 'Edit Slider';
}
$unreadMessagesCount = $pdo->query("SELECT COUNT(*) FROM contact_messages WHERE is_read = 0")->fetchColumn();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $link_url = trim($_POST['link_url'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $active = isset($_POST['active']) ? 1 : 0;
    $image_url = trim($_POST['image_url'] ?? '');

    if (!$title) {
        $_SESSION['error'] = $isRTL ? 'العنوان مطلوب' : 'Title is required';
    } else {
        try {
            // When editing, we want to delete the old image if a new one is uploaded
            $shouldDeleteOld = ($slider['id'] && isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK);
            $image_url = handle_slider_upload($image_url ?: $slider['image_url'], $isRTL, $shouldDeleteOld);

            if (!$image_url) {
                throw new RuntimeException($isRTL ? 'يرجى اختيار صورة للسلايدر.' : 'Please choose a slider image.');
            }

            if ($slider['id']) {
                // Update existing
                $stmt = $pdo->prepare('UPDATE sliders SET title=?, description=?, image_url=?, link_url=?, sort_order=?, active=? WHERE id=?');
                $stmt->execute([$title, $description, $image_url, $link_url, $sort_order, $active, $slider['id']]);
                header('Location: sliders.php?success=edit');
                exit;
            } else {
                // Insert new
                $stmt = $pdo->prepare('INSERT INTO sliders (title, description, image_url, link_url, sort_order, active) VALUES (?, ?, ?, ?, ?, ?)');
                $stmt->execute([$title, $description, $image_url, $link_url, $sort_order, $active]);
                header('Location: sliders.php?success=add');
                exit;
            }
        } catch (Exception $e) {
            $_SESSION['error'] = $isRTL ? 'خطأ: ' . $e->getMessage() : 'Error: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="<?php echo $t['lang']; ?>" dir="<?php echo $t['dir']; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - VAULTIXAI</title>
    <link rel="stylesheet" href="<?php echo $bootstrapCSS; ?>" crossorigin="anonymous">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php
    $currentPage = 'sliders';
    include 'includes/sidebar.php';
    ?>

    <div class="main-content">
        <div class="topbar">
            <h1><?php echo ($slider['id'] ? '✏️ ' : '➕ ') . $pageTitle; ?></h1>
            <a href="sliders.php" class="btn btn-outline-secondary px-4 py-2"><?php echo $t['user_back_btn']; ?></a>
        </div>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger fw-bold mb-4">⚠️ <?php echo htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?></div>
        <?php endif; ?>

        <div class="table-card p-4 p-md-5 mx-auto" style="max-width: 800px;">
            <form method="POST" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-md-8">
                        <label for="title" class="form-label"><?php echo $t['slider_title']; ?> *</label>
                        <input type="text" id="title" name="title" class="form-control form-control-lg" value="<?php echo htmlspecialchars($slider['title']); ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label for="sort_order" class="form-label"><?php echo $isRTL ? 'الترتيب' : 'Sort Order'; ?></label>
                        <input type="number" id="sort_order" name="sort_order" class="form-control form-control-lg" value="<?php echo $slider['sort_order']; ?>">
                    </div>
                </div>

                <div class="mt-3">
                    <label for="description" class="form-label"><?php echo $t['slider_description']; ?></label>
                    <textarea id="description" name="description" class="form-control" rows="3"><?php echo htmlspecialchars($slider['description']); ?></textarea>
                </div>

                <div class="mt-3">
                    <label for="link_url" class="form-label"><?php echo $isRTL ? 'رابط الانتقال' : 'Link URL'; ?></label>
                    <input type="text" id="link_url" name="link_url" class="form-control" value="<?php echo htmlspecialchars($slider['link_url']); ?>" placeholder="services.php">
                </div>

                <div class="mt-4 p-3 border rounded-3 bg-light">
                    <label for="image_file" class="form-label fw-bold"><?php echo $isRTL ? 'صورة السلايدر' : 'Slider Image'; ?></label>
                    <input type="file" id="image_file" name="image_file" class="form-control" accept="image/png,image/jpeg,image/webp,image/gif">
                    <small class="text-muted d-block mt-1"><?php echo $isRTL ? 'اختياري. ارفع ملفاً جديداً لتغيير الصورة الحالية.' : 'Optional. Upload a new file to change the current image.'; ?></small>
                    
                    <input type="hidden" id="image_url" name="image_url" value="<?php echo htmlspecialchars($slider['image_url']); ?>">
                    
                    <img src="<?php echo $slider['image_url'] ? htmlspecialchars(slider_admin_image_src($slider['image_url'])) : ''; ?>" 
                         alt="Image Preview" 
                         class="mt-3 rounded-2 <?php echo $slider['image_url'] ? '' : 'd-none'; ?>" 
                         id="image-preview"
                         style="max-width: 300px; max-height: 150px; object-fit: cover;">
                </div>

                <div class="form-check form-switch mt-4">
                    <input class="form-check-input" type="checkbox" role="switch" id="active" name="active" <?php echo $slider['active'] ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="active"><?php echo $t['slider_active']; ?></label>
                </div>

                <div class="d-flex gap-3 mt-4">
                    <button type="submit" class="btn btn-gold flex-grow-1 py-2 fw-bold fs-6">💾 <?php echo $t['user_save_btn']; ?></button>
                    <a href="sliders.php" class="btn btn-outline-secondary py-2 px-4"><?php echo $t['user_cancel_btn']; ?></a>
                </div>
            </form>
        </div>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
const imagePathInput = document.getElementById('image_url');
const imageFileInput = document.getElementById('image_file');
const preview = document.getElementById('image-preview');

function adminPreviewSrc(value) {
    if (!value) {
        return '';
    }
    if (/^https?:\/\//i.test(value)) {
        return value;
    }
    if (value.indexOf('/') === 0) {
        return value;
    }
    if (value.indexOf('assets/') === 0) {
        return '../public/' + value;
    }
    return value;
}

imagePathInput.addEventListener('change', function() {
    if (this.value) {
        preview.src = adminPreviewSrc(this.value);
        preview.classList.add('active');
    } else {
        preview.classList.remove('active');
    }
});

imageFileInput.addEventListener('change', function() {
    const file = this.files && this.files[0];
    if (!file) {
        return;
    }
    preview.src = URL.createObjectURL(file);
    preview.classList.remove('d-none');
});
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
