<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
if ($method === 'GET') {
    require_permission('finance.view');
    $where = '1=1'; $params=[];
    if (!empty($d['booking_id'])) { $where.=' AND booking_id=?'; $params[]=(int)$d['booking_id']; }
    $s = db()->prepare('SELECT * FROM payments WHERE '.$where.' ORDER BY created_at DESC LIMIT 500');
    $s->execute($params);
    json_ok($s->fetchAll());
}
csrf_check();
if ($method === 'POST') {
    require_permission('finance.manage');
    $errors = v_required($d, ['booking_id','amount']);
    if ($errors) json_error('Validation failed',422,$errors);
    $bid = (int)$d['booking_id']; $amt = v_positive_number($d['amount'], 'amount');
    $pdo = db(); $pdo->beginTransaction();
    try {
        $b = $pdo->prepare('SELECT id,total,currency FROM bookings WHERE id=? FOR UPDATE');
        $b->execute([$bid]);
        $booking = $b->fetch();
        if (!$booking) { $pdo->rollBack(); json_error('Booking not found',404); }
        $currency = substr($booking['currency'] ?: ($d['currency'] ?? 'USD'), 0, 8);
        $ins = $pdo->prepare('INSERT INTO payments (booking_id,amount,currency,method,reference,note,created_by) VALUES (?,?,?,?,?,?,?)');
        $ins->execute([$bid,$amt,$currency,substr($d['method']??'cash',0,40),v_str($d,'reference',100),v_str($d,'note',255),current_user()['id']??null]);
        $pid = $pdo->lastInsertId();
        $sum = $pdo->prepare('SELECT COALESCE(SUM(amount),0) FROM payments WHERE booking_id=?');
        $sum->execute([$bid]); $paid = (float)$sum->fetchColumn();
        $tot = (float)$booking['total'];
        $status = $paid <= 0 ? 'unpaid' : ($paid >= $tot ? 'paid' : 'partial');
        $pdo->prepare('UPDATE bookings SET amount_paid=?, payment_status=? WHERE id=?')->execute([$paid,$status,$bid]);
        $pdo->commit();
        audit('payment.create','payment',$pid);
        json_ok(['id'=>$pid,'payment_status'=>$status]);
    } catch (Throwable $e) { if ($pdo->inTransaction()) $pdo->rollBack(); json_error('Payment failed',500); }
}
json_error('Method not allowed',405);
