<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

auth_start_session();
auth_require_role(['admin']);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

function primary_key_column(PDO $pdo, string $table): string
{
    $stmt = $pdo->prepare(
        "SELECT k.column_name
         FROM information_schema.table_constraints tc
         JOIN information_schema.key_column_usage k
           ON k.constraint_name = tc.constraint_name
          AND k.table_schema = tc.table_schema
          AND k.table_name = tc.table_name
         WHERE tc.table_schema = DATABASE()
           AND tc.table_name = :t
           AND tc.constraint_type = 'PRIMARY KEY'
         ORDER BY k.ordinal_position ASC
         LIMIT 1"
    );
    $stmt->execute(['t' => $table]);
    return (string)($stmt->fetchColumn() ?: '');
}

$id = (int)($_POST['id'] ?? 0);
$status = trim((string)($_POST['status'] ?? ''));

if ($id <= 0 || ($status !== 'approved' && $status !== 'declined')) {
    http_response_code(400);
    echo 'Invalid request';
    exit;
}

function table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.tables
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return (int)$stmt->fetchColumn() > 0;
}

function table_columns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        'SELECT column_name
         FROM information_schema.columns
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function pick_existing_table(PDO $pdo, array $candidates): string
{
    foreach ($candidates as $t) {
        if (table_exists($pdo, $t)) {
            return $t;
        }
    }
    return '';
}

try {
    $pdo = Database::pdo();
    $requestTable = pick_existing_table($pdo, ['subscription_plan_requests', 'plan_requests', 'subscription_requests', 'customer_plan_requests', 'customer_subscriptions']);

    if ($requestTable === '') {
        throw new RuntimeException('Requests table not found.');
    }

    $cols = table_columns($pdo, $requestTable);

    $pkCol = primary_key_column($pdo, $requestTable);
    $idCol = $pkCol !== '' ? $pkCol : (in_array('request_id', $cols, true) ? 'request_id' : (in_array('id', $cols, true) ? 'id' : ''));
    if ($idCol === '') {
        throw new RuntimeException('Could not detect request table primary key column.');
    }
    $statusCol = in_array('status', $cols, true) ? 'status' : '';
    $approvedByCol = in_array('approved_by', $cols, true) ? 'approved_by' : (in_array('resolved_by', $cols, true) ? 'resolved_by' : '');
    $approvedAtCol = in_array('approved_at', $cols, true) ? 'approved_at' : (in_array('updated_at', $cols, true) ? 'updated_at' : '');

    if ($statusCol === '') {
        throw new RuntimeException('Requests table does not have status column.');
    }

    $data = [
        'status' => $status,
        'id' => $id,
    ];

    $set = [$statusCol . ' = :status'];

    if ($approvedByCol !== '') {
        $data['approved_by'] = (int)(auth_user()['user_id'] ?? 0);
        $set[] = $approvedByCol . ' = :approved_by';
    }

    if ($approvedAtCol !== '') {
        $data['approved_at'] = date('Y-m-d H:i:s');
        $set[] = $approvedAtCol . ' = :approved_at';
    }

    $sql = 'UPDATE ' . $requestTable . ' SET ' . implode(', ', $set) . ' WHERE ' . $idCol . ' = :id';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
} catch (Throwable $e) {
    http_response_code(500);
    echo $e->getMessage();
    exit;
}

header('Location: /pest/public/admin/plan_requests.php');
exit;
