<?php
// POST /api/slips/update.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();
$id   = (int)post('id', 0);
if (!$id) apiError('Slip ID required.', 422);

// Fetch existing slip — only owner or admin can edit
$stmt = $db->prepare("SELECT * FROM slips WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$slip = $stmt->fetch();
if (!$slip) apiError('Slip not found.', 404);
if ($slip['user_id'] != $user['id'] && !in_array($user['role_id'], [1, 5])) {
    apiError('Not authorised.', 403);
}

// Handle optional image replacement
$filename  = $slip['filename'];
$origName  = $slip['original_name'];
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);
    // Delete old file if exists
    if ($slip['filename'] && file_exists($dir . $slip['filename'])) {
        @unlink($dir . $slip['filename']);
    }
    $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'];
}

$jobCardId = post('job_card_id') ? (int)post('job_card_id') : null;
$projectId = post('project_id') ? (int)post('project_id') : null;
$status    = $jobCardId ? 'linked' : ($slip['status'] === 'reimbursed' ? 'reimbursed' : 'unlinked');

$db->prepare("
    UPDATE slips SET
        slip_date      = ?,
        merchant       = ?,
        category       = ?,
        amount         = ?,
        vat_amount     = ?,
        payment_method = ?,
        description    = ?,
        filename       = ?,
        original_name  = ?,
        project_id     = ?,
        job_card_id    = ?,
        status         = ?
    WHERE id = ?
")->execute([
    post('slip_date', $slip['slip_date']),
    post('merchant',  $slip['merchant']),
    post('category',  $slip['category']),
    post('amount')    ?: $slip['amount'],
    post('vat_amount') ?: null,
    post('payment_method', $slip['payment_method']),
    post('description', $slip['description']),
    $filename, $origName,
    $projectId, $jobCardId,
    $status,
    $id
]);

apiSuccess(['id' => $id], 'Slip updated.');