<?php
// ─── POST /api/jobcards/payment-add.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();

// jobcard_id can be an integer (regular JC) or a string like PI_1 / PR_1 (pump)
$jobcard_id     = trim($_POST['jobcard_id']    ?? '');
$payment_method = trim($_POST['payment_method'] ?? '');
$amount         = (float) ($_POST['amount']     ?? 0);

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

// Handle optional file upload (EFT proof)
$filename = null;
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.');
    $uploadDir = ROOT . '/uploads/payments/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $filename  = 'payment_' . time() . '_' . preg_replace('/[^a-zA-Z0-9_]/', '', $jobcard_id) . '.' . $ext;
    if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $filename)) {
        Response::error('File upload failed.');
    }
}

if ($payment_method === 'EFT' && !$filename) {
    Response::error('Proof of payment is required for EFT.');
}

$db->run(
    "INSERT INTO jobcard_payments (jobcard_id, payment_method, user_id, amount, file)
     VALUES (?, ?, ?, ?, ?)",
    [$jobcard_id, $payment_method, (int)$user['user_id'], $amount, $filename]
);

$record_id = (int) $db->lastId();

$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 added.');