<?php
/**
 * AJAX: Manually trigger auto-requisition check
 * File: ajax/trigger_auto_requisition.php
 * Method: POST
 */

// Buffer all output — prevents PHP warnings/notices corrupting JSON
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../layouts/dbconn.php';

if (!isset($conn) || !$conn) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Database connection failed.']);
    exit;
}

// Role guard
$allowed_roles = ['PHARM', 'SUPER_ADMIN', 'ADMIN', 'PHARMACIST', 'SUPERADMIN'];
$role_check = $conn->prepare("
    SELECT ur.role_code FROM users u
    JOIN user_roles ur ON u.role_id = ur.role_id
    WHERE u.user_id = ? LIMIT 1
");
$role_check->bind_param("i", $_SESSION['user_id']);
$role_check->execute();
$role_row = $role_check->get_result()->fetch_assoc();

// Allow if role matches OR if Super Admin (some systems use role_name instead of role_code)
if ($role_row) {
    $rc = strtoupper(trim($role_row['role_code'] ?? ''));
    if (!in_array($rc, $allowed_roles)) {
        // Fallback: check role_name
        $rn_check = $conn->prepare("
            SELECT ur.role_name FROM users u
            JOIN user_roles ur ON u.role_id = ur.role_id
            WHERE u.user_id = ? LIMIT 1
        ");
        $rn_check->bind_param("i", $_SESSION['user_id']);
        $rn_check->execute();
        $rn_row = $rn_check->get_result()->fetch_assoc();
        $rn = strtoupper(trim($rn_row['role_name'] ?? ''));
        if (strpos($rn, 'ADMIN') === false && strpos($rn, 'PHARM') === false) {
            ob_end_clean();
            echo json_encode(['success' => false, 'message' => 'Insufficient permissions.']);
            exit;
        }
    }
}

// Ensure the LPO output directory exists
$lpo_dir = dirname(__DIR__) . '/lpo_pdfs/';
if (!is_defined_constant_safe('AREQ_LPO_DIR')) {
    define('AREQ_LPO_DIR', $lpo_dir);
}
if (!is_dir(AREQ_LPO_DIR)) {
    mkdir(AREQ_LPO_DIR, 0755, true);
}

// Load FPDF if available
$fpdf_path = dirname(__DIR__) . '/fpdf/fpdf.php';
if (file_exists($fpdf_path) && !class_exists('FPDF')) {
    require_once $fpdf_path;
}

// Load the LPO PDF generator
$pdf_gen = dirname(__DIR__) . '/generate_lpo_pdf.php';
if (file_exists($pdf_gen)) {
    require_once $pdf_gen;
}

// Load PHPMailer via Composer autoload or direct path
$autoload = dirname(__DIR__) . '/vendor/autoload.php';
if (file_exists($autoload)) {
    require_once $autoload;
}

try {
    // Tell the engine it's being called from an AJAX context
    if (!defined('AREQ_AJAX_CONTEXT')) {
        define('AREQ_AJAX_CONTEXT', true);
    }

    // Run the engine
    $engine = dirname(__DIR__) . '/auto_requisition_check.php';
    if (!file_exists($engine)) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'Engine file not found: auto_requisition_check.php']);
        exit;
    }

    $result = require $engine;

    // If $result isn't an array (e.g. engine returned 1 instead of array), handle gracefully
    if (!is_array($result)) {
        ob_end_clean();
        echo json_encode([
            'success' => true,
            'message' => 'Auto-requisition check completed.',
            'data'    => ['created' => 0, 'emailed' => 0, 'skipped' => 0, 'failed' => 0, 'details' => []]
        ]);
        exit;
    }

    $msg = "Requisitions created: {$result['created']}. "
         . "Emails sent: {$result['emailed']}. "
         . "Skipped (recent req exists): {$result['skipped']}.";

    if (!empty($result['errors'])) {
        $msg .= ' Errors: ' . implode('; ', $result['errors']);
    }

    ob_end_clean();
    echo json_encode([
        'success' => true,
        'message' => $msg,
        'data'    => $result
    ]);

} catch (\Throwable $e) {
    ob_end_clean();
    echo json_encode([
        'success' => false,
        'message' => 'Engine error: ' . $e->getMessage() . ' in ' . basename($e->getFile()) . ':' . $e->getLine()
    ]);
}

// Helper: safe check for defined constant without triggering a notice
function is_defined_constant_safe(string $name): bool {
    return defined($name);
}