<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => 'Gagal menambahkan layanan.', 'errors' => []];

    require_once __DIR__ . '/../../../config/config.php';
    require_once __DIR__ . '/../../../includes/session.php';
    require_once __DIR__ . '/../../../lib/Auth.php';
    require_once __DIR__ . '/../../../includes/functions.php';
    require_once __DIR__ . '/../../../includes/db_connect.php';

    if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
        http_response_code(403);
        $response['message'] = 'Akses ditolak.';
        echo json_encode($response);
        exit;
    }

    if (!isset($pdo) || !$pdo instanceof PDO) {
        http_response_code(500);
        error_log("PDO object not available in admin/add_service.php");
        $response['message'] = 'Koneksi database gagal.';
        echo json_encode($response);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        $response['message'] = 'Metode request tidak valid.';
        echo json_encode($response);
        exit;
    }

    try {
        $categoryId = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
        $providerId = filter_input(INPUT_POST, 'provider_id', FILTER_VALIDATE_INT);
        $providerServiceId = sanitize_input($_POST['provider_service_id'] ?? '');
        $name = sanitize_input($_POST['name'] ?? '');
        $note = sanitize_input($_POST['note'] ?? null); // Bisa null
        $pricePer1000 = filter_input(INPUT_POST, 'price_per_1000', FILTER_VALIDATE_FLOAT);
        $minOrder = filter_input(INPUT_POST, 'min_order', FILTER_VALIDATE_INT);
        $maxOrder = filter_input(INPUT_POST, 'max_order', FILTER_VALIDATE_INT);
        $status = sanitize_input($_POST['status'] ?? 'active');

        $errors = [];

        if (!$categoryId) { $errors['service_category_id'] = 'Kategori wajib dipilih.'; }
        if (!$providerId) { $errors['service_provider_id'] = 'Provider wajib dipilih.'; }
        if (empty($providerServiceId)) { $errors['service_provider_service_id'] = 'ID Layanan Provider wajib diisi.'; }
        if (empty($name)) { $errors['service_name'] = 'Nama layanan wajib diisi.'; }
        if ($pricePer1000 === false || $pricePer1000 < 0) { $errors['service_price_per_1000'] = 'Harga tidak valid.'; }
        if ($minOrder === false || $minOrder < 0) { $errors['service_min_order'] = 'Minimal pesan tidak valid.'; }
        if ($maxOrder === false || $maxOrder < $minOrder) { $errors['service_max_order'] = 'Maksimal pesan tidak valid atau kurang dari minimal.'; }
        if (!in_array($status, ['active', 'inactive'])) { $errors['service_status'] = 'Status tidak valid.'; }

        if (empty($errors)) {
             $stmtCheck = $pdo->prepare("SELECT id FROM services WHERE provider_id = :pid AND provider_service_id = :psid LIMIT 1");
             $stmtCheck->bindParam(':pid', $providerId, PDO::PARAM_INT);
             $stmtCheck->bindParam(':psid', $providerServiceId);
             $stmtCheck->execute();
             if ($stmtCheck->fetch()) {
                 $errors['service_provider_service_id'] = 'ID Layanan Provider ini sudah digunakan untuk provider yang dipilih.';
             }
        }

        if (!empty($errors)) {
            http_response_code(400);
            $response['message'] = 'Periksa kembali input Anda.';
            $response['errors'] = $errors;
        } else {
            $sql = "INSERT INTO services (category_id, provider_id, provider_service_id, name, note, price_per_1000, min_order, max_order, status, created_at, updated_at)
                    VALUES (:cat_id, :prov_id, :prov_svc_id, :name, :note, :price, :min, :max, :status, NOW(), NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':cat_id', $categoryId, PDO::PARAM_INT);
            $stmt->bindParam(':prov_id', $providerId, PDO::PARAM_INT);
            $stmt->bindParam(':prov_svc_id', $providerServiceId);
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':note', $note);
            $stmt->bindParam(':price', $pricePer1000);
            $stmt->bindParam(':min', $minOrder, PDO::PARAM_INT);
            $stmt->bindParam(':max', $maxOrder, PDO::PARAM_INT);
            $stmt->bindParam(':status', $status);

            if ($stmt->execute()) {
                $response['success'] = true;
                $response['message'] = 'Layanan baru berhasil ditambahkan.';
            } else {
                http_response_code(500);
                $response['message'] = 'Gagal menambahkan layanan ke database.';
                error_log("Failed to insert service: " . implode(", ", $stmt->errorInfo()));
            }
        }

    } catch (\PDOException $e) {
        error_log("Admin Add Service DB Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan database.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true && isset($e->errorInfo[1]) && $e->errorInfo[1] == 1062) {
             $response['message'] = "Kombinasi Provider dan ID Layanan Provider sudah ada.";
             $response['errors']['service_provider_service_id'] = 'ID Layanan Provider ini sudah digunakan untuk provider yang dipilih.';
             http_response_code(400);
        } else {
             http_response_code(500);
        }
    } catch (\Throwable $e) {
        error_log("Admin Add Service General Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan internal server.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
        http_response_code(500);
    }

    echo json_encode($response);
    exit;
    ?>
    