<?php
/**
 * API: Upload job photos for an assignment (AJAX endpoint)
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['ok'=>false,'error'=>'Method not allowed']); exit;
}

gp_require_csrf();

$assignmentId = (int)($_POST['assignment_id'] ?? 0);
$userId = (int)(auth_user()['id'] ?? 0);

if ($assignmentId <= 0) {
    http_response_code(422); echo json_encode(['ok'=>false,'error'=>'Missing assignment_id']); exit;
}

// Verify the assignment belongs to this user
$stmt = $pdo->prepare("SELECT id FROM project_assignments WHERE id = :id AND employee_id = (SELECT employee_id FROM users WHERE id = :uid LIMIT 1) LIMIT 1");
$stmt->execute([':id' => $assignmentId, ':uid' => $userId]);
if (!$stmt->fetch()) {
    http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Not authorized']); exit;
}

if (empty($_FILES['job_photo']) || $_FILES['job_photo']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400); echo json_encode(['ok'=>false,'error'=>'No file or upload error: ' . ($_FILES['job_photo']['error'] ?? 'none')]); exit;
}

$file = $_FILES['job_photo'];
$uploadDirFs  = gp_upload_path('job_photos');
$uploadDirWeb = gp_upload_url('job_photos');

$safeName = preg_replace('/[^A-Za-z0-9._-]/', '_', (string)$file['name']);
$stored   = 'assignment_' . $assignmentId . '_' . time() . '_' . bin2hex(random_bytes(4)) . '_' . $safeName;
$fullFs   = rtrim($uploadDirFs, '/\\') . DIRECTORY_SEPARATOR . $stored;

if (!move_uploaded_file($file['tmp_name'], $fullFs)) {
    http_response_code(500); echo json_encode(['ok'=>false,'error'=>'Failed to save file.']); exit;
}

$stmt = $pdo->prepare("INSERT INTO employee_job_photos (project_assignment_id, file_name, file_path) VALUES (:aid, :fname, :fpath)");
$stmt->execute([
    ':aid'   => $assignmentId,
    ':fname' => $safeName,
    ':fpath' => rtrim($uploadDirWeb, '/') . '/' . $stored,
]);

echo json_encode(['ok' => true]);
