<?php
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 = trim((string)($_POST['assignment_id'] ?? '')) ?: null;
$byType = trim((string)($_POST['by_type'] ?? 'employee'));
$partDesc = trim((string)($_POST['part_description'] ?? ''));
$userId = (int)(auth_user()['id'] ?? 0);

if ($projectId <= 0 || $partDesc === '') {
    echo json_encode(['ok'=>false,'error'=>'Project ID and part description are required']); exit;
}
if (!in_array($byType, ['employee','partner'], true)) $byType = 'employee';

// Handle optional photo
$photoFilename = null;
if (isset($_FILES['photo']) && $_FILES['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
    $file = $_FILES['photo'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['ok'=>false,'error'=>'Upload error code: '.$file['error']]); exit;
    }
    $mime = mime_content_type($file['tmp_name']);
    if (strpos((string)$mime, 'image/') !== 0) {
        echo json_encode(['ok'=>false,'error'=>'Only image files are allowed']); exit;
    }
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $photoFilename = 'mp_' . strtolower(bin2hex(random_bytes(8))) . '_' . time() . '.' . $ext;
    $destDir = __DIR__ . '/../uploads/missing_parts/';
    if (!is_dir($destDir)) mkdir($destDir, 0755, true);
    if (!move_uploaded_file($file['tmp_name'], $destDir . $photoFilename)) {
        echo json_encode(['ok'=>false,'error'=>'Could not save uploaded photo']); exit;
    }
}

// Insert request
$stmt = $pdo->prepare("
    INSERT INTO project_missing_parts (project_id, assignment_id, requested_by_user_id, requested_by_type, part_description, photo_filename, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())
");
$stmt->execute([$projectId, $assignmentId, $userId, $byType, $partDesc, $photoFilename]);

// Identify project code/name
$projCode = 'Unknown';
try {
    $ps = $pdo->prepare("SELECT code, title FROM projects WHERE id = ?");
    $ps->execute([$projectId]);
    if ($po = $ps->fetch()) {
        $projCode = $po['code'] . ' - ' . $po['title'];
    }
} catch (Throwable $e) {}

// Fetch manager/admin emails
$mgrEmails = [];
try {
    $ms = $pdo->query("SELECT email FROM users WHERE role IN ('MANAGER','ADMIN') AND is_active = 1 AND email != ''");
    $mgrEmails = $ms->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {}

$senderName = auth_user()['username'] ?? 'Worker';

// Send email to managers
if ($mgrEmails) {
    $to = implode(', ', $mgrEmails);
    $subject = "GoPools CRM: Missing Part Request for Project " . str_replace(["\r","\n"], " ", h($projCode));
    
    $message = "Hello Manager,\n\n";
    $message .= "A new missing part request was submitted by {$senderName} ({$byType}).\n\n";
    $message .= "Project: {$projCode}\n";
    $message .= "Missing Part/Material details:\n";
    $message .= "----------------------------------------\n";
    $message .= $partDesc . "\n";
    $message .= "----------------------------------------\n\n";
    $message .= "Please check the 'Dispatch' page for this project to fulfill the request and provide the tracking number.\n\n";
    $message .= "GoPools CRM Notification System";

    $headers = "From: noreply@gopools.gr\r\n" .
               "Reply-To: noreply@gopools.gr\r\n" .
               "X-Mailer: PHP/" . phpversion();

    @mail($to, $subject, $message, $headers);
}

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