#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Session;
use JSON;
use DBI;
require '/SITES/bjnb/db.pl';

my $q = CGI->new;
my $action = $q->param('action') || '';
my $session = CGI::Session->new(undef, $q, {Directory => '/tmp'});

# Dispatch based on 'action'
if ($action eq 'login') {
    my $username = $q->param('username') // '';
    my $password = $q->param('password') // '';

    my $dbh = get_dbh();
    my $sth = $dbh->prepare("SELECT id, password FROM users WHERE username = ?");
    $sth->execute($username);
    my ($user_id, $stored_hash) = $sth->fetchrow_array;

    print $q->header(-type => 'application/json', -cookie => $session->cookie);
    if ($stored_hash && crypt($password, $stored_hash) eq $stored_hash) {
        $session->param("user_id", $user_id);
        print encode_json({ success => 1 });
    } else {
        print encode_json({ success => 0, error => "Invalid credentials" });
    }

} elsif ($action eq 'check') {
    print $q->header(-type => 'application/json');
    if (my $user_id = $session->param("user_id")) {
        print encode_json({ logged_in => 1, user_id => $user_id });
    } else {
        print encode_json({ logged_in => 0 });
    }

} elsif ($action eq 'logout') {
    $session->delete;
    print $q->header(-type => 'application/json');
    print encode_json({ success => 1 });

} else {
    # Serve SPA HTML shell . only now we print text/html header
    print $q->header(-type => 'text/html');
    print qq{
<!DOCTYPE html>
<html>
<head>
    <title>One Page App</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="/bjnb/static/app.js"></script>
</head>
<body>
    <div id="topbar">
        <span id="greeting"></span>
        <button id="authBtn"></button>
    </div>
    <hr>
    <div id="app"></div>
</body>
</html>
    };
}

