<?php
session_start();
header('Content-Type: application/json');
include_once 'model/services_model.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$service_model = new services_model();

$service_name = $_POST['service_name'] ?? '';
$short_description = $_POST['short_description'] ?? '';
$full_description = $_POST['full_description'] ?? '';
$service_duration = $_POST['service_duration'] ?? '';
$service_cost = $_POST['service_cost'] ?? '';
$service_code = $service_model->generateNextCode();


if (empty($service_name) || empty($short_description) || empty($full_description) || empty($service_duration) || empty($service_cost)) {
    echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
    exit;
}

// Handle image upload
if (!isset($_FILES['service_image']) || $_FILES['service_image']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Image upload failed or missing']);
    exit;
}

$imageTmpPath = $_FILES['service_image']['tmp_name'];
$imageName = basename($_FILES['service_image']['name']);
$imageExt = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));
$allowedExt = ['jpg','jpeg','png','gif'];

if (!in_array($imageExt, $allowedExt)) {
    echo json_encode(['success' => false, 'message' => 'Unsupported image format']);
    exit;
}

$newImageName = uniqid('service_') . '.' . $imageExt;
$uploadPath = __DIR__ . '/../images/services/' . $newImageName;

if (!move_uploaded_file($imageTmpPath, $uploadPath)) {
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded image']);
    exit;
}

// Save service to DB
$added = $service_model->addService([
    'service_code' => $service_code,
    'service_name' => $service_name,
    'short_description' => $short_description,
    'full_description' => $full_description,
    'service_duration' => $service_duration,
    'service_cost' => $service_cost,
    'service_image' => $newImageName,
    'operator' => $_SESSION['sess_usercode']
]);

if ($added) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
