<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}
include '../includes/db.php';

$id = "";
$title = "";
$description = "";
$image_url = "";
$is_edit = false;
$error = "";

// Check if Edit
if (isset($_GET['id'])) {
    $is_edit = true;
    $id = intval($_GET['id']);
    $result = $conn->query("SELECT * FROM services WHERE id=$id");
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $title = $row['title'];
        $description = $row['description'];
        $image_url = $row['image_url'];
    }
}

// Handle Form Submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST['title'];
    $description = $_POST['description'];
    
    // File Upload Logic
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $target_dir = "../uploads/services/";
        // Create directory if not exists (redundant if manually created, but good safety)
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $file_ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($file_ext, $allowed)) {
            $new_filename = uniqid() . '.' . $file_ext;
            $target_file = $target_dir . $new_filename;
            
            if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                // Success: Update image_url path (relative to project root)
                $image_url = "uploads/services/" . $new_filename;
            } else {
                $error = "Failed to upload image.";
            }
        } else {
            $error = "Invalid file type. Only JPG, PNG, GIF allowed.";
        }
    }

    if (!$error) {
        if ($is_edit) {
            // Keep old image if new one isn't uploaded
            $stmt = $conn->prepare("UPDATE services SET title=?, description=?, image_url=? WHERE id=?");
            $stmt->bind_param("sssi", $title, $description, $image_url, $id);
        } else {
            $stmt = $conn->prepare("INSERT INTO services (title, description, image_url) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $title, $description, $image_url);
        }
        
        if ($stmt->execute()) {
            header("Location: manage_services.php");
            exit;
        } else {
            $error = "Database Error: " . $conn->error;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $is_edit ? 'Edit' : 'Add'; ?> Service</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5" style="max-width: 600px;">
        <h3><?php echo $is_edit ? 'Edit' : 'Add New'; ?> Service</h3>
        <?php if($error): ?><div class="alert alert-danger"><?php echo $error; ?></div><?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data">
            <div class="mb-3">
                <label>Service Title</label>
                <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($title); ?>" required>
            </div>
            
            <div class="mb-3">
                <label>Service Image</label>
                <?php if($image_url): ?>
                    <div class="mb-2">
                        <img src="../<?php echo htmlspecialchars($image_url); ?>" width="100" class="img-thumbnail">
                        <small class="d-block text-muted">Current Image</small>
                    </div>
                <?php endif; ?>
                <input type="file" name="image" class="form-control">
                <small class="text-muted">Allowed: JPG, PNG, GIF</small>
            </div>

            <div class="mb-3">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="5" required><?php echo htmlspecialchars($description); ?></textarea>
            </div>
            
            <button type="submit" class="btn btn-success">Save Service</button>
            <a href="manage_services.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</body>
</html>
