<?php
session_start();
require_once '../config/db.php';

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

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

$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone_number'] ?? '');
    $viber = trim($_POST['viber_number'] ?? '');
    $telegram = trim($_POST['telegram_number'] ?? '');
    $fb = trim($_POST['facebook_link'] ?? '');
    $nroiId = trim($_POST['nroi_id'] ?? '');
    $ppsaId = trim($_POST['ppsa_id'] ?? '');
    $emergencyName = capitalizeWords(trim($_POST['emergency_contact_name'] ?? ''));
    $emergencyNumber = trim($_POST['emergency_contact_number'] ?? '');
    $position = trim($_POST['position'] ?? '');

    if (empty($phone)) {
        echo json_encode(['success' => false, 'message' => 'Phone Number is required.']);
        exit;
    }

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

    try {
        $stmt = $pdo->prepare("UPDATE users SET 
            phone_number = ?, 
            viber_number = ?, 
            telegram_number = ?, 
            facebook_link = ?,
            nroi_id = ?,
            ppsa_id = ?,
            emergency_contact_name = ?, 
            emergency_contact_number = ?,
            position = ?
            WHERE id = ?");

        if ($stmt->execute([$phone, $viber, $telegram, $fb, $nroiId, $ppsaId, $emergencyName, $emergencyNumber, $position, $userId])) {
            // Also update session if NROI ID changed
            $_SESSION['nroi_id'] = $nroiId;
            echo json_encode(['success' => true, 'message' => 'Profile updated successfully!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update profile.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>