<?php
// POST /api/slips/create.php
// Handles both plain slips and JC-linked slips with image upload
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user     = requireAuth();
$db       = getDB();
$slipDate = post('slip_date', date('Y-m-d'));
$amount   = (float)post('amount', 0);

if (!$slipDate) apiError('Slip date required.', 422);

$jobCardId = post('job_card_id') ? (int)post('job_card_id') : null;
$projectId = post('project_id') ? (int)post('project_id') : null;
$status    = $jobCardId ? 'linked' : 'unlinked';

// Handle image upload
$filename = null; $origName = null;
if (!empty($_FILES['slip_image']) && $_FILES['slip_image']['error'] === UPLOAD_ERR_OK) {
    $file  = $_FILES['slip_image'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
    $allowed = ['image/jpeg','image/png','image/webp','image/gif','application/pdf'];
    if (!in_array($mime, $allowed)) apiError('Only images or PDF allowed.', 422);
    if ($file['size'] > 15 * 1024 * 1024) apiError('Max 15MB.', 422);
    $dir = __DIR__ . '/../../uploads/slips/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'jpg';
    $filename = 'slip_' . uniqid() . '.' . $ext;
    if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) apiError('Upload failed.', 500);
    $origName = $file['name'];
}

$db->prepare("
    INSERT INTO slips (user_id, slip_date, merchant, category, amount, vat_amount,
                       payment_method, description, filename, original_name,
                       project_id, job_card_id, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
")->execute([
    $user['id'], $slipDate,
    post('merchant'), post('category'),
    $amount ?: null,
    post('vat_amount') ?: null,
    post('payment_method'),
    post('description'),
    $filename, $origName,
    $projectId, $jobCardId,
    $status
]);

apiSuccess(['id' => (int)$db->lastInsertId()], 'Slip saved.', 201);
