<?php
header("Content-Type: application/json");

include_once 'model/services_model.php';

$services_model = new services_model();

try {
    // Validate required POST fields
    $requiredFields = ['service_code', 'service_name', 'short_description', 'full_description', 'service_duration', 'service_cost'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }

    // Sanitize input
    $code = $_POST['service_code'];
    $name = trim($_POST['service_name']);
    $short = trim($_POST['short_description']);
    $full = trim($_POST['full_description']);
    $duration = trim($_POST['service_duration']);
    $cost = floatval($_POST['service_cost']);
    $imageName = null;

    // Check if image was uploaded
    if (!empty($_FILES['service_image']['name'])) {
        $uploadDir = '../images/services/';
        $originalName = basename($_FILES['service_image']['name']);
        $extension = pathinfo($originalName, PATHINFO_EXTENSION);
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (!in_array(strtolower($extension), $allowed)) {
            throw new Exception("Invalid image format. Allowed: JPG, PNG, GIF, WEBP.");
        }

        $imageName = time() . '_' . preg_replace("/[^A-Za-z0-9_\-\.]/", '_', $originalName);
        $uploadPath = $uploadDir . $imageName;

        if (!move_uploaded_file($_FILES['service_image']['tmp_name'], $uploadPath)) {
            throw new Exception("Failed to upload image.");
        }
    }

    // Update using model
    $updated = $services_model->updateService($code, $name, $short, $full, $duration, $cost, $imageName);

    if ($updated) {
        echo json_encode(['success' => true]);
    } else {
        throw new Exception("Service update failed.");
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
