<?php
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';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: services.php');
    exit;
}

$id = (int)$_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM services WHERE id = ?");
$stmt->execute([$id]);
$service = $stmt->fetch();

if (!$service) {
    header('Location: services.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $current_image = trim($_POST['current_image'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $image_url = $current_image;

    if (!empty($name) && !empty($description)) {
        try {
            // Handle image upload
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../public/assets/img/services/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                $filename = uniqid('service-') . '-' . basename($_FILES['image']['name']);
                $uploadFile = $uploadDir . $filename;

                if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
                    $image_url = 'assets/img/services/' . $filename;
                    // Delete old image if a new one is uploaded and an old one exists
                    if (!empty($current_image) && file_exists('../public/' . $current_image)) {
                        unlink('../public/' . $current_image);
                    }
                }
            }

            $stmt = $pdo->prepare("UPDATE services SET name = ?, description = ?, image_url = ?, sort_order = ? WHERE id = ?");
            $stmt->execute([$name, $description, $image_url, $sort_order, $id]);
            header('Location: services.php?success=edit');
            exit;
        } catch (\PDOException $e) {
            $error = ($isRTL ? "حدث خطأ أثناء تعديل الخدمة: " : "Error updating service: ") . $e->getMessage();
        }
    } else {
        $error = $isRTL ? "يرجى ملء جميع الحقول المطلوبة." : "Please fill in all required fields.";
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<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 $t['edit_service_title']; ?> - VAULTIXAI</title>
    <link rel="stylesheet" href="<?php echo $bootstrapCSS; ?>" crossorigin="anonymous">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-brand"><h2>VAULTIXAI</h2></div>
        <nav><ul>
            <li><a href="dashboard.php"><span class="nav-icon">🏠</span><?php echo $t['admin_dashboard']; ?></a></li>
            <li><a href="pages.php"><span class="nav-icon">📄</span><?php echo $t['admin_pages']; ?></a></li>
            <li><a href="certifications.php"><span class="nav-icon">🏆</span><?php echo $t['admin_certifications']; ?></a></li>
            <li><a href="services.php" class="active"><span class="nav-icon">⚙️</span><?php echo $t['admin_services']; ?></a></li>
            <li><a href="sliders.php"><span class="nav-icon">🖼️</span><?php echo $t['admin_sliders']; ?></a></li>
            <li><a href="users.php"><span class="nav-icon">👥</span><?php echo $t['admin_users']; ?></a></li>
        </ul></nav>
        <a href="<?php echo lang_switch_url($t['lang_switch_code']); ?>" class="sidebar-lang-btn">🌐 <?php echo $t['lang_switch_label']; ?></a>
        <div class="sidebar-footer"><a href="logout.php"><span class="nav-icon">🚪</span><?php echo $t['admin_logout']; ?></a></div>
    </div>
    
    <div class="main-content">
        <div class="topbar">
            <h1>✏️ <?php echo $t['edit_service_title']; ?></h1>
            <a href="services.php" class="btn btn-outline-secondary px-4 py-2"><?php echo $t['service_back_btn']; ?></a>
        </div>

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

        <div class="table-card p-4 p-md-5 mx-auto" style="max-width:680px;">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="current_image" value="<?php echo htmlspecialchars($service['image_url'] ?? ''); ?>">
                <div class="mb-3">
                    <label for="name" class="form-label"><?php echo $t['service_name']; ?> *</label>
                    <input type="text" id="name" name="name" class="form-control form-control-lg" required value="<?php echo htmlspecialchars($service['name']); ?>">
                </div>
                
                <div class="mb-4">
                    <label for="description" class="form-label"><?php echo $t['service_description']; ?> *</label>
                    <textarea id="description" name="description" class="form-control form-control-lg" rows="6" required><?php echo htmlspecialchars($service['description']); ?></textarea>
                </div>

                <div class="mb-4">
                    <label for="image" class="form-label"><?php echo $t['service_image']; ?></label>
                    <input type="file" class="form-control" id="image" name="image" accept="image/*">
                    <small class="form-text text-muted"><?php echo $isRTL ? 'اتركه فارغاً للإبقاء على الصورة الحالية.' : 'Leave blank to keep the current image.'; ?></small>
                    <?php if (!empty($service['image_url'])): ?>
                        <div class="mt-2"><small><?php echo $t['cert_current_image']; ?>:</small><br><img src="../public/<?php echo htmlspecialchars($service['image_url']); ?>" alt="Current Image" style="max-width: 150px; height: auto; border-radius: 0.25rem;"></div>
                    <?php endif; ?>
                </div>
                
                <div class="mb-4" style="max-width: 200px;">
                    <label for="sort_order" class="form-label"><?php echo $isRTL ? 'ترتيب العرض' : 'Sort Order'; ?></label>
                    <input type="number" class="form-control" id="sort_order" name="sort_order" value="<?php echo htmlspecialchars($service['sort_order'] ?? 0); ?>">
                </div>

                <div class="d-flex gap-3">
                    <button type="submit" class="btn btn-gold flex-grow-1 py-2 fw-bold fs-6">💾 <?php echo $t['service_save_btn']; ?></button>
                    <a href="services.php" class="btn btn-outline-secondary py-2 px-4"><?php echo $t['service_cancel_btn']; ?></a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Bootstrap 5 JS Bundle CDN -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
</body>
</html>
