<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/helpers/csrf.php';
require_once __DIR__ . '/../app/helpers/mailer.php';
require_once __DIR__ . '/../app/helpers/rbac.php';
require_once __DIR__ . '/../app/helpers/api_security.php';
require_once __DIR__ . '/../config/database.php'; // provides $pdo (PDO)
// load alerts config (returns an array)
$config = require __DIR__ . '/../config/alerts.php';

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

requireApiLogin();
if (!isAdmin() && !can('maintenance.approve') && !can('maintenance.create')) {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

// support multiple actions: invite, resend
$action = $_GET['action'] ?? '';
if (!in_array($action, ['invite', 'resend'], true)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Invalid method']);
    exit;
}

$csrfToken = $_POST['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (!validateCsrfToken($csrfToken)) {
    http_response_code(419);
    echo json_encode(['status' => 'error', 'message' => 'CSRF validation failed']);
    exit;
}

// Incoming values
$workshopEmail = trim((string)($_POST['workshop_email'] ?? ''));
$workshopId = trim((string)($_POST['workshop_id'] ?? ''));
$jobId = trim((string)($_POST['job_id'] ?? ''));

// Resend flow
if ($action === 'resend') {
    $rfqId = isset($_POST['rfq_id']) ? (int)$_POST['rfq_id'] : 0;
    if ($rfqId <= 0) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'rfq_id is required']);
        exit;
    }

    $stmt = $pdo->prepare('SELECT m.*, w.email AS workshop_email, w.name AS workshop_name FROM maintenance_rfqs m LEFT JOIN workshops w ON w.id = m.workshop_id AND w.deleted_at IS NULL WHERE m.id = ? AND m.deleted_at IS NULL LIMIT 1');
    $stmt->execute([$rfqId]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$existing) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'RFQ not found']);
        exit;
    }

    $workshopEmail = $existing['workshop_email'] ?? '';
    $workshopName = $existing['workshop_name'] ?? '';
    $jobId = $existing['maintenance_job_id'] ?? null;

    if (empty($workshopEmail) || !filter_var($workshopEmail, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Workshop email is missing or invalid']);
        exit;
    }

    // rate-limit: prevent resend within last 10 minutes unless force=1
    $force = isset($_POST['force']) && $_POST['force'] == '1';
    $lastUpdated = $existing['updated_at'] ?? $existing['created_at'] ?? null;
    if (!$force && $lastUpdated) {
        $ts = strtotime($lastUpdated);
        if ($ts !== false && (time() - $ts) < 600) {
            echo json_encode(['status' => 'throttled', 'message' => 'Invite was sent recently; wait before resending']);
            exit;
        }
    }

    $jobDetails = fetchRfqJobDetails($pdo, (int)$jobId);

    $subject = 'Request for Quote: ' . ($jobDetails['complaint_title'] ?? 'Maintenance RFQ');
    $msgParts = [];
    $msgParts[] = '<p>Dear ' . htmlspecialchars($workshopName ?? 'Partner', ENT_QUOTES | ENT_SUBSTITUTE) . ',</p>';
    $msgParts[] = '<p>This is a resend of the invitation to provide a quote' . ($jobId ? ' (Job ID: ' . htmlspecialchars((string)$jobId, ENT_QUOTES | ENT_SUBSTITUTE) . ')' : '') . '.</p>';
    if ($jobDetails) {
        $msgParts[] = '<ul>';
        $msgParts[] = '<li><strong>Vehicle:</strong> ' . htmlspecialchars((string)($jobDetails['vehicle'] ?? '-'), ENT_QUOTES | ENT_SUBSTITUTE) . '</li>';
        $msgParts[] = '<li><strong>Title:</strong> ' . htmlspecialchars((string)($jobDetails['complaint_title'] ?? '-'), ENT_QUOTES | ENT_SUBSTITUTE) . '</li>';
        $msgParts[] = '<li><strong>Description:</strong> ' . nl2br(htmlspecialchars((string)($jobDetails['complaint_description'] ?? '-'), ENT_QUOTES | ENT_SUBSTITUTE)) . '</li>';
        $msgParts[] = '</ul>';
    }
    $appUrl = $config['app_url'] ?? (getenv('FLEET_APP_URL') ?: '');
    if ($appUrl && $jobId) {
        $link = rtrim($appUrl, '/') . '/maintenance.php?job_id=' . rawurlencode((string)$jobId);
        $msgParts[] = '<p><a href="' . htmlspecialchars($link, ENT_QUOTES | ENT_SUBSTITUTE) . '">Open job details</a></p>';
    }
    $msgParts[] = '<p>Regards,<br/>Fleet Operations</p>';
    $message = implode("\n", $msgParts);

    $sent = sendMail($workshopEmail, $subject, $message, ['from_name' => 'Fleet Operations']);
    if ($sent) {
        // update rfq_sent_date
        $stmt = $pdo->prepare('UPDATE maintenance_rfqs SET rfq_sent_date = CURDATE(), updated_at = NOW() WHERE id = ?');
        $stmt->execute([$rfqId]);
        echo json_encode(['status' => 'success', 'message' => 'Invite resent']);
    } else {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Failed to resend invite']);
    }
    exit;
}

// If a workshop id is provided, prefer the email on the workshops table.
if ($workshopId !== '') {
    $stmt = $pdo->prepare('SELECT email, name FROM workshops WHERE id = ? AND deleted_at IS NULL LIMIT 1');
    $stmt->execute([(int)$workshopId]);
    $ws = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($ws) {
        // Prefer DB email when present; otherwise fall back to supplied workshop_email
        $dbEmail = trim((string)($ws['email'] ?? ''));
        if ($dbEmail !== '') {
            $workshopEmail = $dbEmail;
        }
        $workshopName = (string)($ws['name'] ?? ($workshopName ?? ''));
    }
}

if (empty($workshopEmail)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Workshop email is required or workshop has no email on file']);
    exit;
}

if (!filter_var($workshopEmail, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid workshop email']);
    exit;
}

try {
    $pdo->beginTransaction();

    $rfqId = 0;
    $rfqNumber = '';

    // Prevent duplicate RFQ for same job + workshop, but still send the invite email.
    if ($jobId !== '' && $workshopId !== '') {
        $stmt = $pdo->prepare('SELECT id, rfq_number FROM maintenance_rfqs WHERE maintenance_job_id = ? AND workshop_id = ? AND status IN (?, ?) AND deleted_at IS NULL LIMIT 1');
        $stmt->execute([(int)$jobId, (int)$workshopId, 'sent', 'quoted']);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($existing) {
            $rfqId = (int)$existing['id'];
            $rfqNumber = (string)($existing['rfq_number'] ?? '');
        }
    }

    if ($rfqId <= 0) {
        $stmt = $pdo->prepare('INSERT INTO maintenance_rfqs (maintenance_job_id, workshop_id, rfq_sent_date, status) VALUES (?, ?, CURDATE(), ?)');
        $stmt->execute([ $jobId !== '' ? (int)$jobId : null, $workshopId !== '' ? (int)$workshopId : null, 'sent' ]);
        $rfqId = (int)$pdo->lastInsertId();

        $rfqNumber = 'RFQ' . date('Ymd') . '-' . str_pad((string)$rfqId, 6, '0', STR_PAD_LEFT);
        $stmt = $pdo->prepare('UPDATE maintenance_rfqs SET rfq_number = ? WHERE id = ?');
        $stmt->execute([$rfqNumber, $rfqId]);
    } elseif ($rfqNumber === '') {
        $rfqNumber = 'RFQ' . date('Ymd') . '-' . str_pad((string)$rfqId, 6, '0', STR_PAD_LEFT);
        $stmt = $pdo->prepare('UPDATE maintenance_rfqs SET rfq_number = ? WHERE id = ?');
        $stmt->execute([$rfqNumber, $rfqId]);
    }

    $jobDetails = fetchRfqJobDetails($pdo, (int)$jobId);

    // Build email
    $subject = 'Request for Quote: ' . ($jobDetails['complaint_title'] ?? 'Maintenance RFQ');
    $msgParts = [];
    $msgParts[] = '<p>Dear ' . htmlspecialchars($workshopName ?? 'Partner', ENT_QUOTES | ENT_SUBSTITUTE) . ',</p>';
    $msgParts[] = '<p>You have been invited to provide a quote for a maintenance job' . ($jobId ? ' (Job ID: ' . htmlspecialchars((string)$jobId, ENT_QUOTES | ENT_SUBSTITUTE) . ')' : '') . '.</p>';
    if ($jobDetails) {
        $msgParts[] = '<ul>';
        $msgParts[] = '<li><strong>Vehicle:</strong> ' . htmlspecialchars((string)($jobDetails['vehicle'] ?? '-'), ENT_QUOTES | ENT_SUBSTITUTE) . '</li>';
        $msgParts[] = '<li><strong>Title:</strong> ' . htmlspecialchars((string)($jobDetails['complaint_title'] ?? '-'), ENT_QUOTES | ENT_SUBSTITUTE) . '</li>';
        $msgParts[] = '<li><strong>Description:</strong> ' . nl2br(htmlspecialchars((string)($jobDetails['complaint_description'] ?? '-'), ENT_QUOTES | ENT_SUBSTITUTE)) . '</li>';
        $msgParts[] = '</ul>';
    }
    $appUrl = $config['app_url'] ?? (getenv('FLEET_APP_URL') ?: '');
    if ($appUrl && $jobId) {
        $link = rtrim($appUrl, '/') . '/maintenance.php?job_id=' . rawurlencode((string)$jobId);
        $msgParts[] = '<p><a href="' . htmlspecialchars($link, ENT_QUOTES | ENT_SUBSTITUTE) . '">Open job details</a></p>';
    }
    $msgParts[] = '<p>RFQ Number: ' . htmlspecialchars($rfqNumber, ENT_QUOTES | ENT_SUBSTITUTE) . '</p>';
    $msgParts[] = '<p>Regards,<br/>Fleet Operations</p>';
    $message = implode("\n", $msgParts);

    $sent = sendMail($workshopEmail, $subject, $message, ['from_name' => 'Fleet Operations']);
    if (!$sent) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Failed to send invitation email']);
        exit;
    }

    $stmt = $pdo->prepare('UPDATE maintenance_rfqs SET rfq_sent_date = CURDATE(), status = IF(status = "quoted", status, "sent"), updated_at = NOW() WHERE id = ?');
    $stmt->execute([$rfqId]);

    $pdo->commit();
    echo json_encode(['status' => 'success', 'message' => 'Invitation sent', 'rfq_id' => $rfqId, 'rfq_number' => $rfqNumber]);
    exit;
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log('RFQ invite error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Server error while creating RFQ invite']);
    exit;
}

function fetchRfqJobDetails(PDO $pdo, int $jobId): ?array
{
    if ($jobId <= 0) {
        return null;
    }

    $stmt = $pdo->prepare("
        SELECT
            mj.id,
            CONCAT_WS(' - ', v.plate_number, NULLIF(CONCAT_WS(' ', NULLIF(v.vehicle_model, ''), NULLIF(v.vehicle_type, '')), '')) AS vehicle,
            mj.complaint_title,
            mj.complaint_description,
            mj.nature_of_fault,
            mj.workflow_stage
        FROM maintenance_jobs mj
        LEFT JOIN vehicles v ON v.id = mj.vehicle_id
        WHERE mj.id = ? AND mj.deleted_at IS NULL
        LIMIT 1
    ");
    $stmt->execute([$jobId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ?: null;
}
