<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal memperbarui 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("Update Provider Error: " . $message);
}


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);
    log_error_message("PDO object not available in admin/update_provider.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 {
    $providerId = filter_input(INPUT_POST, 'provider_id', FILTER_VALIDATE_INT);
    if (!$providerId) {
        throw new InvalidArgumentException('ID provider tidak valid.');
    }

    $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 (!in_array($status, ['active', 'inactive'])) {
        $errors['provider_status'] = 'Status tidak valid.';
        $status = 'active'; // Default jika tidak valid
    }
    if (empty($errors)) {
        try {
            $stmtCheck = $pdo->prepare("SELECT id FROM providers WHERE (name = :name OR api_url = :api_url) AND id != :id LIMIT 1");
            $stmtCheck->bindParam(':name', $name);
            $stmtCheck->bindParam(':api_url', $apiUrl);
            $stmtCheck->bindParam(':id', $providerId, PDO::PARAM_INT);
            $stmtCheck->execute();
            if ($stmtCheck->fetch()) {
                $errors['provider_name'] = 'Nama provider atau API URL sudah digunakan oleh provider lain.';
                 $errors['provider_api_url'] = 'Nama provider atau API URL sudah digunakan oleh provider lain.';
            }
        } 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 {
        $setClauses = [];
        $params = [':id' => $providerId];

        $setClauses[] = "name = :name";
        $params[':name'] = $name;
        $setClauses[] = "api_url = :api_url";
        $params[':api_url'] = $apiUrl;
        $setClauses[] = "api_id = :api_id";
        $params[':api_id'] = $apiId; 
        $setClauses[] = "status = :status";
        $params[':status'] = $status;

        if (!empty($apiKey)) {
            $setClauses[] = "api_key = :api_key";
            $params[':api_key'] = $apiKey;
        }

        if ($secretKey !== null) {
            $setClauses[] = "secret_key = :secret_key";
            $params[':secret_key'] = $secretKey;
        }
        $setClauses[] = "updated_at = NOW()";

        if (count($setClauses) > 1) {
            try {
                $sql = "UPDATE providers SET " . implode(', ', $setClauses) . " WHERE id = :id";
                $stmt = $pdo->prepare($sql);

                if ($stmt->execute($params)) {
                    if ($stmt->rowCount() > 0) {
                        $response['success'] = true;
                        $response['message'] = 'Provider berhasil diperbarui.';
                    } else {
                        $stmtCheckExist = $pdo->prepare("SELECT id FROM providers WHERE id = :id");
                        $stmtCheckExist->bindParam(':id', $providerId, PDO::PARAM_INT);
                        $stmtCheckExist->execute();
                        if ($stmtCheckExist->fetch()) {
                            $response['success'] = true; 
                            $response['message'] = 'Tidak ada perubahan data provider.';
                        } else {
                             http_response_code(404);
                             $response['message'] = 'Provider tidak ditemukan untuk diperbarui.';
                        }
                    }
                } else {
                    http_response_code(500);
                    $response['message'] = 'Gagal memperbarui provider di database.';
                    log_error_message("Failed to update provider ID {$providerId}: " . 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 digunakan oleh provider lain.";
                     $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 update: " . $e->getMessage());
                 } else {
                     http_response_code(500);
                     $response['message'] = "Terjadi kesalahan database saat memperbarui.";
                     log_error_message("Admin Update Provider DB Error on Update: " . $e->getMessage());
                 }
            }
        } else {
             $response['success'] = true;
             $response['message'] = 'Tidak ada data yang perlu diupdate.';
        }
    }

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

echo json_encode($response);
exit;
