<?php
// api/staff_reports.php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';
header('Content-Type: application/json; charset=UTF-8');

function reportRespond($code, $body = null) {
    http_response_code($code);
    if ($body !== null) echo json_encode($body);
    exit;
}

function cleanText($value, $required = false, $max = null) {
    if ($value === null) {
        if ($required) reportRespond(400, ['detail' => 'A required report field is missing.']);
        return '';
    }
    if (!is_string($value) && !is_numeric($value)) {
        reportRespond(400, ['detail' => 'Invalid report field value.']);
    }
    $text = trim((string)$value);
    if ($required && $text === '') reportRespond(400, ['detail' => 'A required report field is empty.']);
    if ($max !== null && strlen($text) > $max) {
        reportRespond(400, ['detail' => 'A report field exceeds the allowed length.']);
    }
    return $text;
}

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS staff_reports (
        id BIGSERIAL PRIMARY KEY,
        lecturer_id BIGINT NULL,
        lecturer_name VARCHAR(255) NOT NULL,
        campus VARCHAR(255) NULL,
        school VARCHAR(255) NULL,
        department VARCHAR(255) NULL,
        reporter_id BIGINT NULL,
        reporter_name VARCHAR(255) NOT NULL,
        reporter_email VARCHAR(255) NULL,
        reporter_phone VARCHAR(80) NULL,
        category VARCHAR(120) NOT NULL,
        subject VARCHAR(255) NOT NULL,
        description TEXT NOT NULL,
        incident_date DATE NULL,
        confidential BOOLEAN NOT NULL DEFAULT TRUE,
        status VARCHAR(40) NOT NULL DEFAULT 'submitted',
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");
    $pdo->exec("ALTER TABLE staff_reports ADD COLUMN IF NOT EXISTS reporter_id BIGINT NULL");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_reports_lecturer_id ON staff_reports (lecturer_id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_reports_reporter_id ON staff_reports (reporter_id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_reports_created_at ON staff_reports (created_at DESC)");

    // Every report request must belong to a real signed-in database account.
    $currentUser = rvu_current_user($pdo);
    if (!$currentUser) {
        reportRespond(401, ['detail' => 'Your session is missing, expired, or invalid. Please sign in again.']);
    }

    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

    if ($method === 'GET') {
        $lecturerId = isset($_GET['lecturer_id']) && ctype_digit((string)$_GET['lecturer_id'])
            ? (int)$_GET['lecturer_id']
            : null;

        if ($lecturerId !== null && $lecturerId > 0) {
            $stmt = $pdo->prepare('SELECT * FROM staff_reports WHERE lecturer_id = ? ORDER BY created_at DESC');
            $stmt->execute([$lecturerId]);
        } else {
            $stmt = $pdo->query('SELECT * FROM staff_reports ORDER BY created_at DESC');
        }
        reportRespond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    if ($method !== 'POST') {
        reportRespond(405, ['detail' => 'Only GET and POST are supported.']);
    }

    $raw = file_get_contents('php://input');
    $input = json_decode($raw, true);
    if (json_last_error() !== JSON_ERROR_NONE || !is_array($input)) {
        reportRespond(400, ['detail' => 'Supply a valid JSON report object.']);
    }

    $lecturerId = null;
    if (array_key_exists('lecturer_id', $input) && $input['lecturer_id'] !== null && $input['lecturer_id'] !== '') {
        if (!ctype_digit((string)$input['lecturer_id']) || (int)$input['lecturer_id'] <= 0) {
            reportRespond(400, ['detail' => 'Invalid lecturer ID.']);
        }
        $lecturerId = (int)$input['lecturer_id'];
    }

    $lecturerName = cleanText($input['lecturer_name'] ?? null, true, 255);
    $campus = cleanText($input['campus'] ?? '', false, 255);
    $school = cleanText($input['school'] ?? '', false, 255);
    $department = cleanText($input['department'] ?? '', false, 255);
    $category = cleanText($input['category'] ?? null, true, 120);
    $subject = cleanText($input['subject'] ?? null, true, 255);
    $description = cleanText($input['description'] ?? null, true, null);

    if (strlen($description) < 20) {
        reportRespond(400, ['detail' => 'Please provide a more detailed report description.']);
    }

    $incidentDate = cleanText($input['incident_date'] ?? '', false, 10);
    if ($incidentDate !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $incidentDate)) {
        reportRespond(400, ['detail' => 'Incident date must use YYYY-MM-DD format.']);
    }
    if ($incidentDate === '') $incidentDate = null;

    $confidential = array_key_exists('confidential', $input) ? (bool)$input['confidential'] : true;

    // SECURITY: reporter identity is never trusted from Flutter form values.
    // It comes from the bearer session -> user_sessions -> users database row.
    $reporterId = (int)$currentUser['id'];
    $reporterName = trim((string)$currentUser['full_name']);
    $reporterEmail = trim((string)$currentUser['email']);
    $reporterPhone = trim((string)($currentUser['phone'] ?? ''));

    if ($reporterId <= 0 || $reporterName === '' || $reporterEmail === '') {
        reportRespond(409, ['detail' => 'The signed-in database account is missing required reporter information.']);
    }

    $stmt = $pdo->prepare("INSERT INTO staff_reports (
        lecturer_id, lecturer_name, campus, school, department,
        reporter_id, reporter_name, reporter_email, reporter_phone,
        category, subject, description, incident_date, confidential
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id");

    $stmt->execute([
        $lecturerId,
        $lecturerName,
        $campus !== '' ? $campus : null,
        $school !== '' ? $school : null,
        $department !== '' ? $department : null,
        $reporterId,
        $reporterName,
        $reporterEmail,
        $reporterPhone !== '' ? $reporterPhone : null,
        $category,
        $subject,
        $description,
        $incidentDate,
        $confidential,
    ]);

    $id = $stmt->fetchColumn();
    reportRespond(201, [
        'message' => 'Lecturer report submitted successfully.',
        'id' => $id,
        'reporter_id' => $reporterId,
    ]);
} catch (PDOException $error) {
    reportRespond(500, ['detail' => 'Database error while saving lecturer report: ' . $error->getMessage()]);
} catch (Throwable $error) {
    reportRespond(500, ['detail' => 'Server error while processing lecturer report: ' . $error->getMessage()]);
}
