<?php
ob_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../../config/database.php';

function square_init_json_response(array $payload): void {
    if (ob_get_length()) {
        $buffer = ob_get_contents();
        if ($buffer !== false && $buffer !== '') {
            error_log('Square init stray output: ' . substr($buffer, 0, 500));
        }
        ob_clean();
    }
    echo json_encode($payload);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    square_init_json_response(['success' => false, 'message' => 'Method not allowed']);
}

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$type = strtolower(trim($input['type'] ?? 'enrollment'));

$enrollmentId = 0;
$appointmentId = 0;
$userId = 0;
if ($type === 'appointment') {
    $appointmentId = (int)($input['appointment_id'] ?? 0);
    if (!$appointmentId) {
        square_init_json_response(['success' => false, 'message' => 'appointment_id required']);
    }
} elseif ($type === 'ai_premium') {
    $userId = (int)($input['user_id'] ?? 0);
    if (!$userId) {
        square_init_json_response(['success' => false, 'message' => 'user_id required']);
    }
} else {
    $enrollmentId = (int)($input['enrollment_id'] ?? 0);
    if (!$enrollmentId) {
        square_init_json_response(['success' => false, 'message' => 'enrollment_id required']);
    }
}

if (!defined('SQUARE_ACCESS_TOKEN') || !SQUARE_ACCESS_TOKEN) {
    square_init_json_response(['success' => false, 'message' => 'Square access token is not configured']);
}

if (!defined('SQUARE_LOCATION_ID') || !SQUARE_LOCATION_ID || strpos(SQUARE_LOCATION_ID, 'your-square-location-id') !== false) {
    square_init_json_response(['success' => false, 'message' => 'Square location ID is not configured']);
}

$db = Database::getInstance();

// Determine payment context and amount/currency
if ($type === 'appointment') {
    $appointment = $db->get('SELECT * FROM appointments WHERE id = ?', [$appointmentId]);
    if (!$appointment) {
        square_init_json_response(['success' => false, 'message' => 'Appointment not found']);
    }

    if (($appointment['payment_status'] ?? 'free') !== 'pending') {
        square_init_json_response(['success' => false, 'message' => 'Appointment not pending payment']);
    }

    $amount = (float)($appointment['amount'] ?? 0.0);
    if ($amount <= 0) {
        square_init_json_response(['success' => false, 'message' => 'Invalid appointment amount']);
    }

    $currency = strtoupper($appointment['currency'] ?? 'USD');
    if (!in_array($currency, ['USD', 'EUR'], true)) {
        square_init_json_response(['success' => false, 'message' => 'Square is only available for USD or EUR appointments.']);
    }

    $itemName = $appointment['topic'] ?? 'Appointment';
    $redirectUrl = APP_URL . '/website/api/square/verify.php?type=appointment&appointment_id=' . $appointmentId;
} elseif ($type === 'ai_premium') {
    $user = $db->get('SELECT id, email FROM users WHERE id = ?', [$userId]);
    if (!$user) {
        square_init_json_response(['success' => false, 'message' => 'User not found']);
    }

    $amount = defined('AI_PREMIUM_PRICE') ? (float)AI_PREMIUM_PRICE : 0.0;
    if ($amount <= 0) {
        square_init_json_response(['success' => false, 'message' => 'Invalid AI Premium amount']);
    }

    $currency = defined('AI_PREMIUM_CURRENCY_SQUARE') ? strtoupper(AI_PREMIUM_CURRENCY_SQUARE) : 'USD';
    if (!in_array($currency, ['USD', 'EUR'], true)) {
        square_init_json_response(['success' => false, 'message' => 'Square AI Premium currency must be USD or EUR']);
    }

    $itemName = 'AI Premium Cybersecurity Copilot';
    $redirectUrl = APP_URL . '/website/api/square/verify.php?type=ai_premium&user_id=' . $userId;
} else {
    $enrollment = $db->get('SELECT ce.*, c.title, c.currency FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id WHERE ce.id = ?', [$enrollmentId]);

    if (!$enrollment) {
        square_init_json_response(['success' => false, 'message' => 'Enrollment not found']);
    }

    if ($enrollment['payment_status'] !== 'pending') {
        square_init_json_response(['success' => false, 'message' => 'Enrollment not pending payment']);
    }

    $agreement = $db->get('SELECT status FROM course_enrollment_agreements WHERE enrollment_id = ?', [$enrollmentId]);
    if (!$agreement || $agreement['status'] !== 'signed') {
        square_init_json_response(['success' => false, 'message' => 'Training agreement must be signed before payment.']);
    }

    $paymentPolicy = $db->get('SELECT status FROM course_enrollment_payment_policies WHERE enrollment_id = ?', [$enrollmentId]);
    if (!$paymentPolicy || $paymentPolicy['status'] !== 'accepted') {
        square_init_json_response(['success' => false, 'message' => 'Non-Refundable Payment Policy must be accepted before payment.']);
    }

    $privacyPolicy = $db->get('SELECT status FROM course_enrollment_privacy_policies WHERE enrollment_id = ?', [$enrollmentId]);
    if (!$privacyPolicy || $privacyPolicy['status'] !== 'accepted') {
        square_init_json_response(['success' => false, 'message' => 'Data Privacy Policy must be accepted before payment.']);
    }

    $amount = (float)($enrollment['payment_amount'] ?? 0.0);
    if ($amount <= 0) {
        square_init_json_response(['success' => false, 'message' => 'Invalid enrollment amount']);
    }

    $currency = strtoupper($enrollment['payment_currency'] ?? ($enrollment['currency'] ?? 'USD'));
    $itemName = $enrollment['title'] ?? 'Course Enrollment';
    $redirectUrl = APP_URL . '/website/api/square/verify.php?enrollment_id=' . $enrollmentId;
}
$base = defined('SQUARE_API_BASE') && SQUARE_API_BASE ? SQUARE_API_BASE : 'https://connect.squareupsandbox.com';
$url = rtrim($base, '/') . '/v2/online-checkout/payment-links';

try {
    $idempotencyKey = bin2hex(random_bytes(16));
} catch (Exception $e) {
    $idempotencyKey = uniqid('sqpl_', true);
}

$body = [
    'idempotency_key' => $idempotencyKey,
    'order' => [
        'location_id' => SQUARE_LOCATION_ID,
        'line_items' => [
            [
                'name' => $itemName,
                'quantity' => '1',
                'base_price_money' => [
                    'amount' => (int)round($amount * 100),
                    'currency' => $currency,
                ],
            ],
        ],
    ],
    'checkout_options' => [
        'redirect_url' => $redirectUrl,
    ],
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . SQUARE_ACCESS_TOKEN,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($body),
]);

$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);

if ($errno) {
    square_init_json_response(['success' => false, 'message' => 'Square init failed: ' . $error]);
}

$data = json_decode($response, true);

if (!is_array($data)) {
    square_init_json_response([
        'success' => false,
        'message' => 'Square returned an invalid response',
        'raw_response' => (defined('APP_ENV') && APP_ENV === 'development') ? $response : null,
    ]);
}

if (empty($data['payment_link']['url'])) {
    // Try to pull out helpful error detail from Square's error format
    $detail = null;
    if (isset($data['errors']) && is_array($data['errors']) && count($data['errors']) > 0) {
        $firstError = $data['errors'][0];
        if (!empty($firstError['detail'])) {
            $detail = $firstError['detail'];
        } elseif (!empty($firstError['code'])) {
            $detail = 'Error code: ' . $firstError['code'];
        }
    }

    $message = 'Unexpected response from Square';
    if ($detail) {
        $message .= ': ' . $detail;
    }

    square_init_json_response([
        'success' => false,
        'message' => $message,
        'response' => (defined('APP_ENV') && APP_ENV === 'development') ? $data : null,
    ]);
}

$checkoutUrl = $data['payment_link']['url'];

square_init_json_response([
    'success' => true,
    'checkout_url' => $checkoutUrl,
]);
