#!/usr/bin/perl
use strict;
use warnings;
use JSON;

use CGI;
use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);
my $cgi = CGI->new;

my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $tt_params;
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'jsonFrm.tmpl',
        }
);


# check form submit
if ( $cgi->param('submit_form') )
{
    my $user_details = get_user_details();
    $tt_params->{user_details} = $user_details;
}

# check if its an AJAX submit
if ( $cgi->param('ajax') ) {
    my $user_details = get_user_details();
    my $json = to_json($user_details);
    print $cgi->header('application/json');
    print $json;
    exit;
}
print $cgi->header('text/html');

sub get_user_details
{
    # pretend like we're doing some heavy task!
    sleep 1;

    my $user_details = {
        first_name => 'Bob',
        last_name  => 'Green',
        sex        => 'M',
        age        => 35,
    };
  return $user_details;
}

tmpl_write($dbh, $cgi, $cookie, $template);


