<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function getUserFile() {
    return __DIR__ . DIRECTORY_SEPARATOR . 'users.json';
}

function loadUsers() {
    $file = getUserFile();
    if (!file_exists($file)) {
        return [];
    }
    $json = file_get_contents($file);
    $data = $json ? json_decode($json, true) : [];
    if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
        return [];
    }
    return $data;
}

function saveUsers($users) {
    $file = getUserFile();
    file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}

function findUserByEmail($email) {
    $users = loadUsers();
    foreach ($users as $user) {
        if (strcasecmp($user['email'], $email) === 0) {
            return $user;
        }
    }
    return null;
}

function registerUser($firstName, $lastName, $email, $password) {
    $users = loadUsers();
    if (findUserByEmail($email) !== null) {
        return 'A user with that email already exists.';
    }
    $users[] = [
        'first_name' => $firstName,
        'last_name' => $lastName,
        'email' => $email,
        'password' => password_hash($password, PASSWORD_DEFAULT),
        'created_at' => date('c')
    ];
    saveUsers($users);
    return true;
}

function authenticateUser($email, $password) {
    $user = findUserByEmail($email);
    if (!$user) {
        return null;
    }
    return password_verify($password, $user['password']) ? $user : null;
}

function getBookingFile() {
    return __DIR__ . DIRECTORY_SEPARATOR . 'bookings.json';
}

function loadBookings() {
    $file = getBookingFile();
    if (!file_exists($file)) {
        return [];
    }
    $json = file_get_contents($file);
    $data = $json ? json_decode($json, true) : [];
    if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
        return [];
    }
    return $data;
}

function saveBookings($bookings) {
    $file = getBookingFile();
    file_put_contents($file, json_encode($bookings, JSON_PRETTY_PRINT));
}

function getBookings($email) {
    $bookings = loadBookings();
    return array_values(array_filter($bookings, function ($booking) use ($email) {
        return isset($booking['agent_email']) && strcasecmp($booking['agent_email'], $email) === 0;
    }));
}

function updateBooking($id, $updates) {
    $bookings = loadBookings();
    foreach ($bookings as &$booking) {
        if (isset($booking['id']) && $booking['id'] === $id) {
            $booking = array_merge($booking, $updates);
            saveBookings($bookings);
            return $booking;
        }
    }
    return null;
}

function getHxLogFile() {
    return __DIR__ . DIRECTORY_SEPARATOR . 'hx_logs.json';
}

function loadHxLogs() {
    $file = getHxLogFile();
    if (!file_exists($file)) {
        return [];
    }
    $json = file_get_contents($file);
    $data = $json ? json_decode($json, true) : [];
    if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
        return [];
    }
    return $data;
}

function saveHxLogs($logs) {
    $file = getHxLogFile();
    file_put_contents($file, json_encode($logs, JSON_PRETTY_PRINT));
}

function addHxLog($log) {
    $logs = loadHxLogs();
    $log['id'] = uniqid('log_');
    $log['created_at'] = date('c');
    $logs[] = $log;
    saveHxLogs($logs);
    return $log;
}

function getAgentHxLogs($email) {
    $logs = loadHxLogs();
    return array_values(array_filter($logs, function ($log) use ($email) {
        return isset($log['agent_email']) && strcasecmp($log['agent_email'], $email) === 0;
    }));
}

function getQueueBadgeCount($email) {
    $logs = getAgentHxLogs($email);
    return count(array_filter($logs, function ($log) {
        return empty($log['seen']);
    }));
}

function getQueueSummary($email) {
    $bookings = getBookings($email);
    $summary = [
        'total' => count($bookings),
        'unresolved' => 0,
        'hx_detected' => 0,
        'un_detected' => 0,
        'pending_removal' => 0,
        'escalations' => 0,
    ];
    foreach ($bookings as $booking) {
        if (empty($booking['removed'])) {
            $summary['unresolved']++;
        }
        if (!empty($booking['hx_detected'])) {
            $summary['hx_detected']++;
        }
        if (!empty($booking['un_detected'])) {
            $summary['un_detected']++;
        }
        if (empty($booking['ticketed']) || empty($booking['paid'])) {
            $summary['pending_removal']++;
        }
        if (!empty($booking['status']) && strtolower($booking['status']) === 'escalated') {
            $summary['escalations']++;
        }
    }
    return $summary;
}

function processHxQueue($agentEmail) {
    $bookings = loadBookings();
    $summary = [
        'detected_hx' => 0,
        'detected_un' => 0,
        'auto_removed' => 0,
        'auto_escalated' => 0,
        'notifications' => 0,
    ];
    foreach ($bookings as &$booking) {
        if (!isset($booking['agent_email']) || strcasecmp($booking['agent_email'], $agentEmail) !== 0) {
            continue;
        }
        $changed = false;
        if (empty($booking['hx_detected']) && !empty($booking['pnr']) && preg_match('/^[A-Z0-9]{6}$/', $booking['pnr'])) {
            $booking['hx_detected'] = true;
            addHxLog([
                'agent_email' => $agentEmail,
                'booking_id' => $booking['id'],
                'type' => 'HX detection',
                'level' => 'INFO',
                'message' => 'Automatic HX detected from PNR feed.',
                'auto' => true,
                'is_notification' => true,
            ]);
            $summary['detected_hx']++;
            $changed = true;
        }
        if (empty($booking['un_detected']) && !empty($booking['pnr_un'])) {
            $booking['un_detected'] = true;
            addHxLog([
                'agent_email' => $agentEmail,
                'booking_id' => $booking['id'],
                'type' => 'UN detection',
                'level' => 'INFO',
                'message' => 'Automatic UN detected from PNR feed.',
                'auto' => true,
                'is_notification' => true,
            ]);
            $summary['detected_un']++;
            $changed = true;
        }
        $age = isset($booking['created_at']) ? max(0, time() - strtotime($booking['created_at'])) : 0;
        if (empty($booking['removed']) && empty($booking['ticketed']) && $age > 3 * 86400) {
            $booking['removed'] = true;
            $booking['status'] = 'Removed';
            addHxLog([
                'agent_email' => $agentEmail,
                'booking_id' => $booking['id'],
                'type' => 'Auto removal',
                'level' => 'ALERT',
                'message' => 'Non-ticketed booking auto-removed by HX engine.',
                'auto' => true,
                'email_sent' => true,
                'is_notification' => true,
            ]);
            $summary['auto_removed']++;
            $changed = true;
        }
        if (empty($booking['removed']) && empty($booking['paid']) && $age > 5 * 86400) {
            $booking['removed'] = true;
            $booking['status'] = 'Removed';
            addHxLog([
                'agent_email' => $agentEmail,
                'booking_id' => $booking['id'],
                'type' => 'Auto removal',
                'level' => 'ALERT',
                'message' => 'Unpaid booking auto-removed by HX engine.',
                'auto' => true,
                'email_sent' => true,
                'is_notification' => true,
            ]);
            $summary['auto_removed']++;
            $changed = true;
        }
        if ($changed) {
            $booking['last_processed_at'] = date('c');
        }
    }
    saveBookings($bookings);
    return $summary;
}

function escalateBooking($bookingId, $agentEmail, $reason) {
    $booking = updateBooking($bookingId, [
        'status' => 'Escalated',
        'escalated_at' => date('c'),
        'escalation_reason' => $reason,
    ]);
    if ($booking) {
        addHxLog([
            'agent_email' => $agentEmail,
            'booking_id' => $bookingId,
            'type' => 'Escalation',
            'level' => 'ALERT',
            'message' => 'Booking manually escalated: ' . $reason,
            'auto' => false,
            'email_sent' => true,
            'is_notification' => true,
        ]);
    }
    return $booking;
}

function removeBooking($bookingId, $agentEmail, $reason) {
    $booking = updateBooking($bookingId, [
        'removed' => true,
        'status' => 'Removed',
        'removed_at' => date('c'),
        'removal_reason' => $reason,
    ]);
    if ($booking) {
        addHxLog([
            'agent_email' => $agentEmail,
            'booking_id' => $bookingId,
            'type' => 'Manual removal',
            'level' => 'ALERT',
            'message' => 'Booking manually removed: ' . $reason,
            'auto' => false,
            'email_sent' => true,
            'is_notification' => true,
        ]);
    }
    return $booking;
}

function sendBookingNotification($bookingId, $agentEmail, $note) {
    $booking = updateBooking($bookingId, [
        'last_notified_at' => date('c'),
    ]);
    if ($booking) {
        addHxLog([
            'agent_email' => $agentEmail,
            'booking_id' => $bookingId,
            'type' => 'Queue notification',
            'level' => 'INFO',
            'message' => 'Notification sent to owning agent and team lead: ' . $note,
            'auto' => false,
            'is_notification' => true,
        ]);
    }
    return $booking;
}

function redirect($url) {
    header('Location: ' . $url);
    exit;
}
?>
