<?php
/**
 * API: Upload project photos from partner/employee portal
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.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();

$projectId    = (int)($_POST['project_id'] ?? 0);
$assignmentId = (int)($_POST['assignment_id'] ?? 0) ?: null;
$category     = trim((string)($_POST['category'] ?? 'pool'));
$byType       = trim((string)($_POST['by_type'] ?? 'employee'));

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

if (!in_array($category, ['pool','mechanical'], true)) $category = 'pool';
if (!in_array($byType, ['employee','partner'], true)) $byType = 'employee';

// Safely get user ID
$userId = (int)(auth_user()['id'] ?? 0);

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

$file = $_FILES['photo'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png','gif','webp'];
if (!in_array($ext, $allowed, true)) {
    http_response_code(400); echo json_encode(['ok'=>false,'error'=>'Only images allowed (jpg, png, webp, gif).']); exit;
}

$uploadDir = gp_upload_path('project_photos');

$newFilename = 'proj_' . $projectId . '_' . uniqid() . '.' . $ext;
$dest = $uploadDir . '/' . $newFilename;

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

$stmt = $pdo->prepare("
    INSERT INTO project_photos
    (project_id, assignment_id, uploaded_by_user_id, uploaded_by_type, category, filename, original_name, file_size, mime_type)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
    $projectId,
    $assignmentId,
    $userId,
    $byType,
    $category,
    $newFilename,
    $file['name'],
    (int)$file['size'],
    $file['type'] ?: mime_content_type($dest)
]);

$photoId = (int)$pdo->lastInsertId();

// Log action to notify admin
gp_log_action($pdo, 'PHOTO_UPLOAD', 'project', $projectId, "Προστέθηκε νέα φωτογραφία στο έργο (Κατηγορία: $category)");

// Optional: resize image if it's too large, but for now we'll accept it as-is.

echo json_encode(['ok' => true, 'photo_id' => $photoId, 'filename' => $newFilename, 'category' => $category]);
