<?php
/**
 * NROI Profile Update API (Robust Version)
 * Completely self-contained to avoid output leaks from includes.
 */
ob_start();
error_reporting(0);
@ini_set('display_errors', 0);
@ini_set('html_errors', 0);

// Set timezone to Philippines (UTC+8)
date_default_timezone_set('Asia/Manila');

// 1. Manually set CORS headers (similar to cors.php)
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowOrigin = '*';
if ($origin && (strpos($origin, 'http://localhost') === 0 || strpos($origin, 'http://127.0.0.1') === 0)) {
    $allowOrigin = $origin;
}
header("Access-Control-Allow-Origin: $allowOrigin");
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    header('Access-Control-Max-Age: 86400');
    header('Content-Length: 0');
    http_response_code(204);
    ob_end_clean();
    exit;
}

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

$response = ['status' => 'error', 'message' => 'Unknown error'];

try {
    if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
        $user_id = $_POST['user_id'] ?? '';

        if (empty($user_id)) {
            $response = ['status' => 'error', 'message' => 'User ID is required'];
        } else {
            require_once '../config/db.php';

            $email = trim($_POST['email'] ?? '');
            $phone_number = trim($_POST['phone_number'] ?? '');
            $facebook_link = trim($_POST['facebook_link'] ?? '');
            $viber_number = trim($_POST['viber_number'] ?? '');
            $telegram_number = trim($_POST['telegram_number'] ?? '');
            $emergency_contact_name = trim($_POST['emergency_contact_name'] ?? '');
            $emergency_contact_number = trim($_POST['emergency_contact_number'] ?? '');
            $nroi_id = trim($_POST['nroi_id'] ?? '');
            $ppsa_id = trim($_POST['ppsa_id'] ?? '');

            // Check if NROI ID is already taken by another user
            if (!empty($nroi_id)) {
                $checkStmt = $pdo->prepare("SELECT id FROM users WHERE nroi_id = ? AND id != ?");
                $checkStmt->execute([$nroi_id, $user_id]);
                if ($checkStmt->fetch()) {
                    $response = ['status' => 'error', 'message' => 'NROI ID already in use by another account'];
                    ob_end_clean();
                    echo json_encode($response);
                    exit;
                }
            }

            // Helper to capitalize words (mirroring db.php function)
            if (!empty($emergency_contact_name)) {
                $emergency_contact_name = ucwords(strtolower(trim($emergency_contact_name)));
            }

            // 2. Determine if user is OJT to restrict editing
            $rankStmt = $pdo->prepare("SELECT rank FROM users WHERE id = ?");
            $rankStmt->execute([$user_id]);
            $currentRank = strtoupper($rankStmt->fetchColumn() ?: '');
            $isOJT = (strpos($currentRank, 'OJT') !== false);

            if ($isOJT) {
                // OJT users cannot edit NROI ID and PPSA ID
                $stmt = $pdo->prepare("UPDATE users SET 
                    phone_number = ?, 
                    facebook_link = ?, 
                    viber_number = ?, 
                    telegram_number = ?, 
                    emergency_contact_name = ?, 
                    emergency_contact_number = ?
                    WHERE id = ?");

                $result = $stmt->execute([
                    $phone_number,
                    $facebook_link,
                    $viber_number,
                    $telegram_number,
                    $emergency_contact_name,
                    $emergency_contact_number,
                    $user_id
                ]);
            } else {
                // Regular users can update NROI and PPSA
                $stmt = $pdo->prepare("UPDATE users SET 
                    phone_number = ?, 
                    facebook_link = ?, 
                    viber_number = ?, 
                    telegram_number = ?, 
                    emergency_contact_name = ?, 
                    emergency_contact_number = ?,
                    nroi_id = ?,
                    ppsa_id = ?
                    WHERE id = ?");

                $result = $stmt->execute([
                    $phone_number,
                    $facebook_link,
                    $viber_number,
                    $telegram_number,
                    $emergency_contact_name,
                    $emergency_contact_number,
                    $nroi_id,
                    $ppsa_id,
                    $user_id
                ]);
            }

            if ($result) {
                $response = ['status' => 'success', 'message' => 'Profile updated successfully'];
            } else {
                $response = ['status' => 'error', 'message' => 'Database update failed'];
            }
        }
    } else {
        $response = ['status' => 'error', 'message' => 'Invalid request method'];
    }
} catch (Throwable $e) {
    $response = ['status' => 'error', 'message' => 'System error: ' . $e->getMessage()];
}

// Clear any accidental output (warnings, notices, etc.)
if (ob_get_length()) {
    ob_end_clean();
}
echo json_encode($response);
exit;