<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';

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

auth_require_customer_portal();
$pdo = crm_pdo();
$userId = (int)(auth_user()['id'] ?? 0);
$customerId = auth_customer_id();

header('Content-Type: application/json; charset=utf-8');

try {
    gp_require_csrf_api();

    $projectId = (int)($_POST['project_id'] ?? 0);
    $category = trim((string)($_POST['category'] ?? 'other'));
    $title = trim((string)($_POST['title'] ?? ''));

    if ($projectId <= 0) {
        throw new Exception('Invalid project selection.');
    }

    // Verify customer owns this project!
    $stmtOwner = $pdo->prepare("SELECT id FROM projects WHERE id = :pid AND customer_id = :cid");
    $stmtOwner->execute([':pid' => $projectId, ':cid' => $customerId]);
    if (!$stmtOwner->fetch()) {
        throw new Exception('Unauthorized or invalid project.');
    }

    if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No photo file uploaded or upload error.');
    }

    $file = $_FILES['photo'];
    $maxSize = 25 * 1024 * 1024; // 25MB
    if ($file['size'] > $maxSize) {
        throw new Exception('File size exceeds the 25MB limit.');
    }

    $allowedMimes = ['image/jpeg', 'image/png', 'image/webp'];
    $mime = mime_content_type($file['tmp_name']);
    if (!in_array($mime, $allowedMimes, true)) {
        throw new Exception('Only JPG, PNG and WEBP images are allowed.');
    }

    $uploadDir = __DIR__ . '/../uploads/photos';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    if (!preg_match('/^[a-zA-Z0-9]+$/', $ext)) $ext = 'jpg';
    $filename = 'customer_' . $projectId . '_' . time() . '_' . substr(md5(random_bytes(16)), 0, 8) . '.' . $ext;
    $dest = $uploadDir . '/' . $filename;

    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        throw new Exception('Failed to save the uploaded photo to disk.');
    }

    $stmt = $pdo->prepare("
        INSERT INTO project_photos 
        (project_id, uploaded_by_user_id, uploaded_by_type, category, title, filename, original_name, file_size, mime_type, shared_with_crew) 
        VALUES (:pid, :uid, 'customer', :category, :title, :fname, :orig, :fsize, :mime, 0)
    ");
    $stmt->execute([
        ':pid' => $projectId,
        ':uid' => $userId,
        ':category' => $category,
        ':title' => $title !== '' ? $title : null,
        ':fname' => $filename,
        ':orig' => $file['name'],
        ':fsize' => $file['size'],
        ':mime' => $mime
    ]);

    // Send an in-app notification to all Admins & Moderators when a customer uploads a photo
    $photoId = $pdo->lastInsertId();
    try {
        $admins = $pdo->query("SELECT u.id FROM users u JOIN user_roles ur ON u.role_id = ur.id WHERE ur.is_admin = 1 OR ur.role_key IN ('manager', 'secretary')")->fetchAll();
        $notifStmt = $pdo->prepare("INSERT INTO user_notifications (user_id, type_key, related_id, title, context_data) VALUES (?, ?, ?, ?, ?)");
        
        $notifTitle = 'Customer uploaded a photo for project #' . $projectId;
        $context = json_encode(['project_id' => $projectId, 'photo_id' => $photoId]);

        foreach ($admins as $admin) {
            $notifStmt->execute([ $admin['id'], 'customer_photo', $photoId, $notifTitle, $context ]);
        }
    } catch (Throwable $e) {}

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

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
