<?php
register_shutdown_function('handleShutdown');

function handleShutdown() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        ob_clean();
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Fatal Error: ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line']
        ]);
    }
}

ob_start();
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');
error_reporting(E_ALL);

// ── JSON response ─────────────────────────────────────────────
function jsonResponse($success, $message, $data = []) {
    while (ob_get_level()) ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $data));
    exit;
}

// ── Send HTML email ───────────────────────────────────────────
// Key fixes vs previous version:
//  1. From address changed from noreply@ to a real inbox — noreply@ fails SPF on most shared hosts
//  2. Removed @ error suppressor so failures are captured in error.log
//  3. Added -f envelope sender param — prevents SPF soft-fail on cPanel/shared hosting
//  4. Added Return-Path and Message-ID headers for better deliverability
//  5. $to is plain email only (no "Name <email>") — avoids header mangling for admin
function sendMail($to_email, $subject, $html_body) {
    $from_email = 'editorial.office@communeglobal.com'; // must be a real inbox on your server
    $from_name  = 'Communeglobal Editorial Office';

    if (!filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
        error_log("sendMail SKIP: invalid address — $to_email");
        return false;
    }

    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
    $headers .= 'From: =?UTF-8?B?' . base64_encode($from_name) . '?= <' . $from_email . '>' . "\r\n";
    $headers .= 'Reply-To: ' . $from_email . "\r\n";
    $headers .= 'Return-Path: ' . $from_email . "\r\n";
    $headers .= 'X-Mailer: PHP/' . phpversion() . "\r\n";
    $headers .= 'Message-ID: <' . time() . '.' . md5($to_email . $subject) . '@communeglobal.com>';

    $encoded_subject   = '=?UTF-8?B?' . base64_encode($subject) . '?=';
    $additional_params = '-f' . $from_email; // envelope sender — fixes SPF on cPanel hosts

    $sent = mail($to_email, $encoded_subject, $html_body, $headers, $additional_params);

    if (!$sent) {
        $err = error_get_last();
        error_log("sendMail FAILED to $to_email | $subject | PHP error: " . ($err['message'] ?? 'none'));
    } else {
        error_log("sendMail OK to $to_email | $subject");
    }

    return $sent;
}

// ── Applicant confirmation email ──────────────────────────────
function sendApplicantEmail($app_id, $full_name, $to_email, $research_areas) {
    $subject = 'Reviewer Application Received - ' . $app_id . ' | Communeglobal';

    $areas_html = '';
    foreach ($research_areas as $area) {
        $areas_html .= '<li style="padding:3px 0;color:#374151;">' . htmlspecialchars($area) . '</li>';
    }

    $html = '<!DOCTYPE html>
<html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;background:#f3f4f6;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f6;padding:40px 0;">
<tr><td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
  <tr>
    <td style="background:#003366;padding:32px 40px;text-align:center;">
      <h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Communeglobal</h1>
      <p style="margin:6px 0 0;color:#93c5fd;font-size:13px;">Peer-Reviewed Open Access Publishing</p>
    </td>
  </tr>
  <tr>
    <td style="padding:36px 40px;">
      <p style="margin:0 0 16px;font-size:15px;color:#111827;">Dear <strong>' . htmlspecialchars($full_name) . '</strong>,</p>
      <p style="margin:0 0 16px;font-size:14px;color:#374151;line-height:1.7;">
        Thank you for applying to join the Communeglobal reviewer panel. We have successfully received your application and our editorial team will review it shortly.
      </p>
      <table width="100%" cellpadding="0" cellspacing="0" style="margin:24px 0;">
        <tr>
          <td style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;padding:20px;text-align:center;">
            <p style="margin:0 0 6px;font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:1px;">Your Application ID</p>
            <p style="margin:0;font-size:24px;font-weight:700;color:#1d4ed8;letter-spacing:2px;">' . htmlspecialchars($app_id) . '</p>
            <p style="margin:6px 0 0;font-size:12px;color:#6b7280;">Please keep this for your records</p>
          </td>
        </tr>
      </table>
      <p style="margin:0 0 8px;font-size:14px;font-weight:600;color:#111827;">Research Areas Submitted:</p>
      <ul style="margin:0 0 20px;padding-left:20px;">' . $areas_html . '</ul>
      <table width="100%" cellpadding="0" cellspacing="0" style="margin:20px 0;">
        <tr>
          <td style="background:#f9fafb;border-left:4px solid #003366;border-radius:0 6px 6px 0;padding:16px 20px;">
            <p style="margin:0 0 8px;font-size:13px;font-weight:700;color:#003366;">What happens next?</p>
            <ul style="margin:0;padding-left:18px;">
              <li style="font-size:13px;color:#374151;padding:3px 0;">Our editorial team will review your application (typically within 5-7 business days).</li>
              <li style="font-size:13px;color:#374151;padding:3px 0;">You will receive an email notification once a decision has been made.</li>
              <li style="font-size:13px;color:#374151;padding:3px 0;">If approved, you will be added to our reviewer panel and may receive manuscript assignments.</li>
            </ul>
          </td>
        </tr>
      </table>
      <p style="margin:24px 0 0;font-size:14px;color:#374151;line-height:1.7;">
        If you have any questions, please contact us at
        <a href="mailto:editorial.office@communeglobal.com" style="color:#1d4ed8;">editorial.office@communeglobal.com</a>.
      </p>
      <p style="margin:20px 0 0;font-size:14px;color:#374151;">
        Warm regards,<br><strong>Editorial Office</strong><br>Communeglobal International Journals
      </p>
    </td>
  </tr>
  <tr>
    <td style="background:#f9fafb;border-top:1px solid #e5e7eb;padding:20px 40px;text-align:center;">
      <p style="margin:0;font-size:12px;color:#9ca3af;">
        &copy; ' . date('Y') . ' Communeglobal. All rights reserved.<br>
        <a href="https://communeglobal.com" style="color:#6b7280;">communeglobal.com</a>
      </p>
    </td>
  </tr>
</table>
</td></tr>
</table>
</body></html>';

    return sendMail($to_email, $subject, $html);
}

// ── Admin notification email ──────────────────────────────────
// FIX: argument order corrected — $how_find_us is param 12, $mobile_no is param 13
// (previous version had them swapped which caused a silent type mismatch)
function sendAdminEmail(
    $app_id, $full_name, $applicant_email,
    $salutation, $gender,
    $current_employment, $total_experience, $educational_qualifications,
    $city, $country, $international_publications,
    $how_find_us,
    $mobile_no,
    $research_areas, $refs
) {
    $admin_email = 'editorialoffice@rsis-international.org';
    $subject     = '[New Reviewer Application] ' . $app_id . ' - ' . $full_name;

    $areas_html = '';
    foreach ($research_areas as $i => $area) {
        $bg = ($i % 2 === 0) ? '#f9fafb' : '#ffffff';
        $areas_html .= '<tr style="background:' . $bg . ';">
          <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Area ' . ($i + 1) . '</td>
          <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($area) . '</td>
        </tr>';
    }

    $html = '<!DOCTYPE html>
<html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;background:#f3f4f6;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f6;padding:40px 0;">
<tr><td align="center">
<table width="620" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
  <tr>
    <td style="background:#1e293b;padding:24px 32px;">
      <p style="margin:0;font-size:11px;color:#94a3b8;text-transform:uppercase;letter-spacing:1px;">Admin Notification</p>
      <h1 style="margin:6px 0 0;color:#ffffff;font-size:18px;">New Reviewer Application</h1>
    </td>
  </tr>
  <tr>
    <td style="background:#003366;padding:14px 32px;">
      <p style="margin:0;font-size:13px;color:#93c5fd;">
        Application ID: <strong style="color:#ffffff;font-size:15px;letter-spacing:1px;">' . htmlspecialchars($app_id) . '</strong>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        Received: <strong style="color:#ffffff;">' . date('d M Y, h:i A') . '</strong>
      </p>
    </td>
  </tr>
  <tr><td style="padding:28px 32px;">

    <p style="margin:0 0 12px;font-size:14px;font-weight:700;color:#111827;border-bottom:2px solid #e5e7eb;padding-bottom:8px;">Personal Information</p>
    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:20px;">
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;width:40%;">Full Name</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;font-weight:600;">' . htmlspecialchars($salutation . ' ' . $full_name) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Gender</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($gender) . '</td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Email</td>
        <td style="padding:8px 12px;font-size:13px;"><a href="mailto:' . htmlspecialchars($applicant_email) . '" style="color:#1d4ed8;">' . htmlspecialchars($applicant_email) . '</a></td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Mobile</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($mobile_no) . '</td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Location</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($city . ', ' . $country) . '</td>
      </tr>
    </table>

    <p style="margin:0 0 12px;font-size:14px;font-weight:700;color:#111827;border-bottom:2px solid #e5e7eb;padding-bottom:8px;">Professional Information</p>
    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:20px;">
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;width:40%;">Employment</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($current_employment) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Experience</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($total_experience) . ' years</td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Qualifications</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($educational_qualifications) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Publications</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($international_publications) . '</td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Found Us Via</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($how_find_us) . '</td>
      </tr>
    </table>

    <p style="margin:0 0 12px;font-size:14px;font-weight:700;color:#111827;border-bottom:2px solid #e5e7eb;padding-bottom:8px;">Research Areas</p>
    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:20px;">' . $areas_html . '</table>

    <p style="margin:0 0 12px;font-size:14px;font-weight:700;color:#111827;border-bottom:2px solid #e5e7eb;padding-bottom:8px;">References</p>
    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:24px;">
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;width:40%;">Ref 1 - Name</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($refs['ref1']['name']) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 1 - Email</td>
        <td style="padding:8px 12px;font-size:13px;"><a href="mailto:' . htmlspecialchars($refs['ref1']['email']) . '" style="color:#1d4ed8;">' . htmlspecialchars($refs['ref1']['email']) . '</a></td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 1 - Org</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($refs['ref1']['org']) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 1 - Mobile</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($refs['ref1']['mobile']) . '</td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 2 - Name</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($refs['ref2']['name']) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 2 - Email</td>
        <td style="padding:8px 12px;font-size:13px;"><a href="mailto:' . htmlspecialchars($refs['ref2']['email']) . '" style="color:#1d4ed8;">' . htmlspecialchars($refs['ref2']['email']) . '</a></td>
      </tr>
      <tr style="background:#f9fafb;">
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 2 - Org</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($refs['ref2']['org']) . '</td>
      </tr>
      <tr>
        <td style="padding:8px 12px;font-size:13px;color:#6b7280;">Ref 2 - Mobile</td>
        <td style="padding:8px 12px;font-size:13px;color:#111827;">' . htmlspecialchars($refs['ref2']['mobile']) . '</td>
      </tr>
    </table>

    <table width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td align="center" style="padding:8px 0;">
          <a href="https://communeglobal.com/admin/reviewers_applications.php"
             style="display:inline-block;background:#003366;color:#ffffff;text-decoration:none;padding:12px 32px;border-radius:6px;font-size:14px;font-weight:600;">
            Review Application in Admin Panel
          </a>
        </td>
      </tr>
    </table>

  </td></tr>
  <tr>
    <td style="background:#f9fafb;border-top:1px solid #e5e7eb;padding:16px 32px;text-align:center;">
      <p style="margin:0;font-size:12px;color:#9ca3af;">
        Automated notification from Communeglobal Editorial System<br>
        &copy; ' . date('Y') . ' Communeglobal
      </p>
    </td>
  </tr>
</table>
</td></tr>
</table>
</body></html>';

    return sendMail($admin_email, $subject, $html);
}


// ── Main logic ────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method');
}

try {
    if (session_status() === PHP_SESSION_NONE) session_start();

    error_log('=== REVIEWER APPLICATION START ===');

    $db_host = 'localhost';
    $db_user = 'u427625983_schoolinmycity';
    $db_pass = 'K#$%^tfvgyt657guvgGG';
    $db_name = 'u427625983_schoolinmycity';

    $db = new mysqli($db_host, $db_user, $db_pass, $db_name);
    if ($db->connect_error) {
        jsonResponse(false, 'DB Connection Error: ' . $db->connect_error);
    }
    $db->set_charset('utf8mb4');

    $required = [
        'salutation', 'full_name', 'gender', 'current_employment',
        'total_experience', 'educational_qualifications',
        'research_area_1', 'research_area_2', 'research_area_3', 'research_area_4',
        'institutional_email', 'personal_email', 'mobile_no', 'whatsapp_no',
        'city', 'country', 'international_publications', 'how_find_us',
        'reference_1_name', 'reference_1_email', 'reference_1_organization', 'reference_1_mobile',
        'reference_2_name', 'reference_2_email', 'reference_2_organization', 'reference_2_mobile'
    ];

    $errors = [];
    foreach ($required as $field) {
        if (!isset($_POST[$field]) || trim($_POST[$field]) === '') {
            $errors[$field] = 'This field is required';
        }
    }

    foreach (['institutional_email', 'personal_email', 'reference_1_email', 'reference_2_email'] as $field) {
        if (!empty($_POST[$field]) && !filter_var($_POST[$field], FILTER_VALIDATE_EMAIL)) {
            $errors[$field] = 'Invalid email format';
        }
    }

    if (isset($_POST['gender']) && !in_array($_POST['gender'], ['Male', 'Female', 'Other'])) {
        $errors['gender'] = 'Invalid gender value';
    }
    if (!isset($_POST['agree_terms'])) {
        $errors['agree_terms'] = 'You must agree to terms';
    }

    $cv_url = null;
    if (!isset($_FILES['cv_file']) || $_FILES['cv_file']['error'] !== UPLOAD_ERR_OK) {
        $errors['cv_file'] = 'CV file is required (Error: ' . (isset($_FILES['cv_file']) ? $_FILES['cv_file']['error'] : 'No file') . ')';
    } else {
        $file = $_FILES['cv_file'];
        $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['pdf', 'doc', 'docx'])) {
            $errors['cv_file'] = 'Only PDF, DOC, DOCX allowed';
        } elseif ($file['size'] > 5242880) {
            $errors['cv_file'] = 'File too large (max 5MB)';
        } else {
            $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/reviewers_cv/';
            if (!is_dir($upload_dir) && !mkdir($upload_dir, 0755, true)) {
                $errors['cv_file'] = 'Failed to create upload directory';
            }
            if (empty($errors['cv_file'])) {
                $filename = uniqid('cv_', true) . '.' . $ext;
                if (move_uploaded_file($file['tmp_name'], $upload_dir . $filename)) {
                    $cv_url = 'uploads/reviewers_cv/' . $filename;
                } else {
                    $errors['cv_file'] = 'Upload failed';
                }
            }
        }
    }

    if (!empty($errors)) {
        jsonResponse(false, 'Please correct the following errors', ['errors' => $errors]);
    }

    $app_id     = 'REV-' . date('Y') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    $journal_id = isset($_SESSION['journal_id']) ? intval($_SESSION['journal_id']) : 1;

    $areas = [];
    for ($i = 1; $i <= 8; $i++) {
        if (!empty($_POST['research_area_' . $i])) {
            $areas[] = trim($_POST['research_area_' . $i]);
        }
    }
    $research_areas_json = json_encode($areas);

    $refs = [
        'ref1' => [
            'name'   => trim($_POST['reference_1_name']),
            'email'  => trim($_POST['reference_1_email']),
            'org'    => trim($_POST['reference_1_organization']),
            'mobile' => trim($_POST['reference_1_mobile'])
        ],
        'ref2' => [
            'name'   => trim($_POST['reference_2_name']),
            'email'  => trim($_POST['reference_2_email']),
            'org'    => trim($_POST['reference_2_organization']),
            'mobile' => trim($_POST['reference_2_mobile'])
        ]
    ];
    $reviewer_references_json = json_encode($refs);

    $salutation                 = trim($_POST['salutation']);
    $full_name                  = trim($_POST['full_name']);
    $gender                     = trim($_POST['gender']);
    $current_employment         = trim($_POST['current_employment']);
    $total_experience           = intval($_POST['total_experience']);
    $educational_qualifications = trim($_POST['educational_qualifications']);
    $institutional_email        = trim($_POST['institutional_email']);
    $personal_email             = trim($_POST['personal_email']);
    $mobile_no                  = trim($_POST['mobile_no']);
    $whatsapp_no                = trim($_POST['whatsapp_no']);
    $city                       = trim($_POST['city']);
    $country                    = trim($_POST['country']);
    $international_publications = intval($_POST['international_publications']);
    $how_find_us                = trim($_POST['how_find_us']);
    $status                     = 0;

    $sql = "INSERT INTO review_application (
        journal_id, application_id, salutation, full_name, gender,
        current_employment, total_experience, educational_qualifications,
        research_areas, institutional_email, personal_email, mobile_no,
        whatsapp_no, city, country, international_publications,
        how_find_us, cv_url, reviewer_references, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $db->prepare($sql);
    if (!$stmt) {
        jsonResponse(false, 'SQL Prepare Error: ' . $db->error);
    }

    $stmt->bind_param('isssssississsssisssi',
        $journal_id, $app_id, $salutation, $full_name, $gender,
        $current_employment, $total_experience, $educational_qualifications,
        $research_areas_json, $institutional_email, $personal_email, $mobile_no,
        $whatsapp_no, $city, $country, $international_publications,
        $how_find_us, $cv_url, $reviewer_references_json, $status
    );

    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        $db->close();
        jsonResponse(false, 'Execute Error: ' . $err);
    }

    $insert_id = $stmt->insert_id;
    $stmt->close();
    $db->close();

    error_log("DB insert OK — insert_id: $insert_id | app_id: $app_id");

    // Applicant email goes to institutional, fallback to personal
    $applicant_email = !empty($institutional_email) ? $institutional_email : $personal_email;

    $sent_applicant = sendApplicantEmail($app_id, $full_name, $applicant_email, $areas);

    // Admin email — $how_find_us at position 12, $mobile_no at position 13
    $sent_admin = sendAdminEmail(
        $app_id, $full_name, $applicant_email,
        $salutation, $gender,
        $current_employment, $total_experience, $educational_qualifications,
        $city, $country, $international_publications,
        $how_find_us,
        $mobile_no,
        $areas, $refs
    );

    error_log("Email results — Applicant: " . ($sent_applicant ? 'YES' : 'NO') . " | Admin: " . ($sent_admin ? 'YES' : 'NO'));

    jsonResponse(true,
        'Application submitted successfully! Your Application ID is: ' . $app_id .
        '. A confirmation email has been sent to ' . $applicant_email . '.',
        ['application_id' => $app_id, 'insert_id' => $insert_id]
    );

} catch (Exception $e) {
    error_log('Exception: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    jsonResponse(false, 'Exception: ' . $e->getMessage());
} catch (Error $e) {
    error_log('Error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    jsonResponse(false, 'Error: ' . $e->getMessage());
}
?>