<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Database;
use App\Core\Response;
use App\Core\Security;

$user = Auth::requireUser();
if (!Auth::hasPermission('payments.manage', $user)) {
    Response::error('You do not have permission to manage payment methods.', 403);
}

$pdo = Database::connection();
$input = request_input();
$method = $_SERVER['REQUEST_METHOD'];
$action = $input['action'] ?? 'list';

function pyrk_payment_methods_table_ready(PDO $pdo): bool
{
    try {
        $pdo->query('SELECT 1 FROM payment_methods LIMIT 1');
        return true;
    } catch (Throwable) {
        return false;
    }
}

function pyrk_payment_method_code(string $value): string
{
    $code = strtolower(trim($value));
    $code = preg_replace('/[^a-z0-9_]+/', '_', $code);
    $code = trim((string)$code, '_');
    return substr($code, 0, 50);
}

function pyrk_payment_methods_require_table(PDO $pdo): void
{
    if (!pyrk_payment_methods_table_ready($pdo)) {
        Response::error('Payment methods table is not installed. Run database/migrations/045_payment_methods_manageable.sql', 500);
    }
}

if ($method === 'GET' && $action === 'list') {
    pyrk_payment_methods_require_table($pdo);

    $rows = $pdo->query('SELECT pm.*,
            (SELECT COUNT(*) FROM walk_payments wp WHERE wp.payment_type = pm.code) AS usage_count
        FROM payment_methods pm
        ORDER BY pm.sort_order ASC, pm.name ASC')->fetchAll(PDO::FETCH_ASSOC);

    Response::ok(['methods' => $rows]);
}

if ($method === 'POST' && in_array($action, ['save', 'create', 'update'], true)) {
    pyrk_payment_methods_require_table($pdo);
    Csrf::validateFromRequest();

    $id = (int)($input['id'] ?? 0);
    $name = trim((string)($input['name'] ?? ''));
    $code = pyrk_payment_method_code((string)($input['code'] ?? $name));
    $status = strtolower(trim((string)($input['status'] ?? 'active')));
    $sort = (int)($input['sort_order'] ?? 100);

    if ($name === '') Response::error('Payment method name is required.');
    if ($code === '') Response::error('Payment method code is required.');
    if (!in_array($status, ['active', 'inactive'], true)) $status = 'active';

    try {
        if ($id > 0) {
            $beforeStmt = $pdo->prepare('SELECT * FROM payment_methods WHERE id = ? LIMIT 1');
            $beforeStmt->execute([$id]);
            $before = $beforeStmt->fetch(PDO::FETCH_ASSOC);
            if (!$before) Response::error('Payment method not found.', 404);

            $stmt = $pdo->prepare('UPDATE payment_methods SET code = ?, name = ?, status = ?, sort_order = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$code, $name, $status, $sort, $id]);
            Security::audit((int)$user['id'], 'payment_method_updated', 'payment_methods', $id, ['code' => $code, 'name' => $name, 'status' => $status], $before);
            Response::ok(['id' => $id], 'Payment method updated.');
        }

        $stmt = $pdo->prepare('INSERT INTO payment_methods (code, name, status, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())');
        $stmt->execute([$code, $name, $status, $sort]);
        $newId = (int)$pdo->lastInsertId();
        Security::audit((int)$user['id'], 'payment_method_created', 'payment_methods', $newId, ['code' => $code, 'name' => $name, 'status' => $status]);
        Response::ok(['id' => $newId], 'Payment method created.');
    } catch (Throwable $e) {
        if (str_contains($e->getMessage(), 'Duplicate')) Response::error('This payment method code already exists.');
        Response::error('Could not save payment method: ' . $e->getMessage());
    }
}

if ($method === 'POST' && $action === 'delete') {
    pyrk_payment_methods_require_table($pdo);
    Csrf::validateFromRequest();

    $id = (int)($input['id'] ?? 0);
    if (!$id) Response::error('Missing payment method id.');

    $stmt = $pdo->prepare('SELECT * FROM payment_methods WHERE id = ? LIMIT 1');
    $stmt->execute([$id]);
    $before = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$before) Response::error('Payment method not found.', 404);

    $usage = $pdo->prepare('SELECT COUNT(*) FROM walk_payments WHERE payment_type = ?');
    $usage->execute([(string)$before['code']]);
    $usageCount = (int)$usage->fetchColumn();

    if ($usageCount > 0) {
        $pdo->prepare('UPDATE payment_methods SET status = "inactive", updated_at = NOW() WHERE id = ?')->execute([$id]);
        Security::audit((int)$user['id'], 'payment_method_deactivated', 'payment_methods', $id, ['usage_count' => $usageCount], $before);
        Response::ok([], 'Payment method is used by receipts, so it was deactivated instead of deleted.');
    }

    $pdo->prepare('DELETE FROM payment_methods WHERE id = ?')->execute([$id]);
    Security::audit((int)$user['id'], 'payment_method_deleted', 'payment_methods', $id, null, $before);
    Response::ok([], 'Payment method deleted.');
}

Response::error('Unsupported payment method action.', 404);
