<?php
// ─── POST /api/jobcards/payment-update.php ────────────────────────────────
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

$user = Auth::require();
$db   = DB::get();

$record_id      = (int)   ($_POST['record_id']       ?? 0);
$payment_method = trim($_POST['payment_method']       ?? '');
$amount         = (float) ($_POST['amount']           ?? 0);

if (!$record_id)      Response::error('record_id is required.');
if (!$payment_method) Response::error('Payment method is required.');
if ($amount <= 0)     Response::error('Amount must be greater than 0.');

// Get existing payment to check/replace file
$existing = $db->row("SELECT * FROM jobcard_payments WHERE record_id = ?", [$record_id]);
if (!$existing) Response::error('Payment not found.', 404);

$filename = $existing['file']; // keep existing file by default

// Handle new file upload
if (!empty($_FILES['file']['tmp_name'])) {
    $ext     = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','pdf','webp'];
    if (!in_array($ext, $allowed)) Response::error('Invalid file type. Allowed: jpg, png, pdf.');
    $uploadDir = ROOT . '/uploads/payments/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $newFile = 'payment_' . time() . '_' . $existing['jobcard_id'] . '.' . $ext;
    if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $newFile)) {
        Response::error('File upload failed.');
    }
    // Delete old file if it exists
    if ($existing['file'] && file_exists($uploadDir . $existing['file'])) {
        @unlink($uploadDir . $existing['file']);
    }
    $filename = $newFile;
}

// If EFT and no file at all, reject
if ($payment_method === 'EFT' && !$filename) {
    Response::error('Proof of payment is required for EFT.');
}

$db->run(
    "UPDATE jobcard_payments SET payment_method = ?, amount = ?, file = ? WHERE record_id = ?",
    [$payment_method, $amount, $filename, $record_id]
);

$payment = $db->row(
    "SELECT jp.*, u.username
     FROM jobcard_payments jp
     LEFT JOIN users u ON u.record_id = jp.user_id
     WHERE jp.record_id = ?",
    [$record_id]
);

Response::ok($payment, 'Payment updated.');