<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal menambahkan provider.', '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';

function log_error_message($message) {
    error_log("Add Provider Error: " . $message);
}

if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    $response['message'] = 'Akses ditolak.';
    log_error_message("Akses ditolak (bukan admin). User ID: " . ($_SESSION['user_id'] ?? 'N/A'));
    echo json_encode($response);
    exit;
}

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

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

try {
    $name = sanitize_input($_POST['name'] ?? '');
    $apiUrlInput = trim($_POST['api_url'] ?? '');
    $apiId = isset($_POST['api_id']) && $_POST['api_id'] !== '' ? sanitize_input($_POST['api_id']) : null;
    $apiKey = trim($_POST['api_key'] ?? ''); 
    $secretKey = isset($_POST['secret_key']) && $_POST['secret_key'] !== '' ? trim($_POST['secret_key']) : null;
    $status = sanitize_input($_POST['status'] ?? 'active');

    $errors = [];

    if (empty($name)) {
        $errors['provider_name'] = 'Nama provider wajib diisi.';
    } elseif (mb_strlen($name) > 100) {
        $errors['provider_name'] = 'Nama provider terlalu panjang (maks 100 karakter).';
    }

    $apiUrl = null;
    if (empty($apiUrlInput)) {
        $errors['provider_api_url'] = 'API URL wajib diisi.';
    } else {
        $apiUrlFiltered = filter_var($apiUrlInput, FILTER_SANITIZE_URL);
        if (!filter_var($apiUrlFiltered, FILTER_VALIDATE_URL)) {
            $errors['provider_api_url'] = 'Format API URL tidak valid.';
        } else {
            $apiUrl = $apiUrlFiltered; 
            if (substr($apiUrl, -4) === '/api' && substr($apiUrl, -5) !== '/api/') {
                $apiUrl .= '/';
            }
            if (substr($apiUrl, -5) !== '/api/') {
                 $errors['provider_api_url'] = "API URL harus valid dan diakhiri dengan '/api/'. Contoh: https://domain.com/api/";
            }
        }
    }

    if (empty($apiKey)) {
        $errors['provider_api_key'] = 'API Key wajib diisi.';
    }

    if (!in_array($status, ['active', 'inactive'])) {
        $errors['provider_status'] = 'Status tidak valid.';
        $status = 'active'; 
    }

    if (empty($errors)) {
        try {
            $stmtCheck = $pdo->prepare("SELECT id FROM providers WHERE name = :name OR api_url = :api_url LIMIT 1");
            $stmtCheck->bindParam(':name', $name);
            $stmtCheck->bindParam(':api_url', $apiUrl);
            $stmtCheck->execute();
            if ($stmtCheck->fetch()) {
                $errors['provider_name'] = 'Nama provider atau API URL ini sudah digunakan.';
                $errors['provider_api_url'] = 'Nama provider atau API URL ini sudah digunakan.';
            }
        } catch (\PDOException $e) {
            log_error_message("DB Error checking duplicates: " . $e->getMessage());
            throw new \PDOException("Gagal memeriksa duplikasi data provider.", 0, $e); 
        }
    }

    if (!empty($errors)) {
        http_response_code(400);
        $response['message'] = 'Periksa kembali input Anda.';
        $response['errors'] = $errors;
        log_error_message("Validation errors: " . json_encode($errors));
    } else {
        try {
            $sql = "INSERT INTO providers (name, api_url, api_id, api_key, secret_key, status, created_at, updated_at)
                    VALUES (:name, :api_url, :api_id, :api_key, :secret_key, :status, NOW(), NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':api_url', $apiUrl); 
            $stmt->bindParam(':api_id', $apiId); 
            $stmt->bindParam(':api_key', $apiKey);
            $stmt->bindParam(':secret_key', $secretKey);
            $stmt->bindParam(':status', $status);

            if ($stmt->execute()) {
                $response['success'] = true;
                $response['message'] = 'Provider baru berhasil ditambahkan.';
            } else {
                http_response_code(500);
                $response['message'] = 'Gagal menambahkan provider ke database karena kesalahan server.';
                log_error_message("Failed to insert provider. PDO Error: " . implode(", ", $stmt->errorInfo()));
            }
        } catch (\PDOException $e) {
             if ($e->getCode() == 23000 || (isset($e->errorInfo[1]) && $e->errorInfo[1] == 1062)) {
                 http_response_code(400); 
                 $response['message'] = "Nama provider atau API URL sudah ada.";
                 $response['errors']['provider_name'] = 'Nama provider atau API URL sudah digunakan.';
                 $response['errors']['provider_api_url'] = 'Nama provider atau API URL sudah digunakan.';
                 log_error_message("Duplicate entry on insert: " . $e->getMessage());
             } else {
                 http_response_code(500);
                 $response['message'] = "Terjadi kesalahan database saat menyimpan.";
                 log_error_message("Admin Add Provider DB Error on Insert: " . $e->getMessage());
             }
        }
    }

} catch (\Throwable $e) { 
    http_response_code(500);
    $response['message'] = "Terjadi kesalahan internal server.";
    log_error_message("Admin Add Provider General Error: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) {
        $response['debug_php'] = $e->getMessage();
        $response['debug_trace'] = $e->getTraceAsString(); 
    }
}

echo json_encode($response);
exit;
