<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user      = requireAuth();
$db        = getDB();
$jobCardId = (int)post('job_card_id', 0);
if (!$jobCardId) apiError('Job card ID required.', 422);

if (post('action') === 'delete') {
    $imgId = (int)post('image_id', 0);
    $stmt  = $db->prepare("SELECT filename, file_path FROM job_card_images WHERE id=? AND job_card_id=?");
    $stmt->execute([$imgId, $jobCardId]);
    $img = $stmt->fetch();
    if ($img) {
        $path = !empty($img['file_path'])
            ? __DIR__ . '/../../' . $img['file_path']
            : __DIR__ . '/../../uploads/jobcards/' . $jobCardId . '/' . $img['filename'];
        if (file_exists($path)) unlink($path);
    }
    $db->prepare("DELETE FROM job_card_images WHERE id=? AND job_card_id=?")->execute([$imgId, $jobCardId]);
    apiSuccess([], 'Image deleted.');
}

if (empty($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    $errCode = $_FILES['image']['error'] ?? 'no file';
    apiError('No image received (error: ' . $errCode . ').', 422);
}

$file    = $_FILES['image'];
$allowed = ['image/jpeg','image/png','image/gif','image/webp'];
$finfo   = finfo_open(FILEINFO_MIME_TYPE);
$mime    = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!in_array($mime, $allowed)) apiError('Only JPG, PNG, GIF, WEBP allowed.', 422);
if ($file['size'] > 15 * 1024 * 1024) apiError('Max file size is 15MB.', 422);

$dir = __DIR__ . '/../../uploads/jobcards/' . $jobCardId . '/';
if (!is_dir($dir)) {
    if (!mkdir($dir, 0755, true)) apiError('Could not create upload directory.', 500);
}

$ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'jpg';
$filename = uniqid('jc_', true) . '.' . $ext;
$dest     = $dir . $filename;

if (!move_uploaded_file($file['tmp_name'], $dest)) apiError('Upload failed — check directory permissions.', 500);

$relPath  = 'uploads/jobcards/' . $jobCardId . '/' . $filename;
$imgType  = post('image_type', 'other');
$caption  = post('caption', '');

$db->prepare("
    INSERT INTO job_card_images (job_card_id, user_id, uploaded_by, filename, original_name, file_path, image_type, caption)
    VALUES (?,?,?,?,?,?,?,?)
")->execute([$jobCardId, $user['id'], $user['id'], $filename, $file['name'], $relPath, $imgType, $caption]);

apiSuccess([
    'id'         => (int)$db->lastInsertId(),
    'file_path'  => $relPath,
    'filename'   => $filename,
    'caption'    => $caption,
    'image_type' => $imgType,
], 'Photo uploaded.', 201);
