<?php
require('fpdf.php');
$pdf = new FPDF();

include $_SERVER['DOCUMENT_ROOT'] . "/WebBuilder/main.class.php";
$db = new DBMain();

$booking_res = $db->exec_query('bookings', ['*'], '', '', '', '', "record_id = {$_GET['record_id']}");
$booking = $booking_res->fetch_assoc();

$client_res = $db->exec_query('clients', ['*'], '', '', '', '', "record_id = {$booking['clients_id']}");
$client = $client_res->fetch_assoc();

function get_username($record_id)
{
    $db = new DBMain();
    $user_res = $db->exec_query('safesure_users', ['*'], '', '', '', '', "record_id = $record_id");
    $user = $user_res->fetch_assoc();
    return $user['safesure_users_name'];
}

function getAgeFromSAID($idNumber)
{
    // South African ID Number must be 13 digits
    if (!preg_match('/^\d{13}$/', $idNumber)) {
        return '';
    }

    // Extract birth date components
    $year = substr($idNumber, 0, 2);
    $month = substr($idNumber, 2, 2);
    $day = substr($idNumber, 4, 2);

    // Determine if the century is 1900 or 2000 based on the current year
    $currentYear = date('Y');
    $century = ($year > substr($currentYear, 2)) ? '19' : '20';
    $birthDate = $century . $year . '-' . $month . '-' . $day;

    // Validate the birth date
    if (!checkdate($month, $day, $century . $year)) {
        return '';
    }

    // Luhn algorithm to validate the ID number
    if (!validateLuhn($idNumber)) {
        return '';
    }

    // Calculate age
    $birthDateTime = new DateTime($birthDate);
    $currentDateTime = new DateTime();
    $ageInterval = $currentDateTime->diff($birthDateTime);

    return $ageInterval->y;
}

function validateLuhn($idNumber)
{
    $sum = 0;
    $shouldDouble = false;

    // Process each digit, starting from the rightmost
    for ($i = strlen($idNumber) - 1; $i >= 0; $i--) {
        $digit = $idNumber[$i];

        if ($shouldDouble) {
            $digit *= 2;
            if ($digit > 9) {
                $digit -= 9;
            }
        }

        $sum += $digit;
        $shouldDouble = !$shouldDouble;
    }

    return ($sum % 10) === 0;
}
function getGenderFromSAID($idNumber)
{
    // South African ID Number must be 13 digits
    if (!preg_match('/^\d{13}$/', $idNumber)) {
        return '';
    }

    // Luhn algorithm to validate the ID number
    if (!validateLuhn($idNumber)) {
        return '';
    }

    // Extract the gender digit (seventh digit in the ID)
    $genderDigit = (int) substr($idNumber, 6, 1);

    // Determine gender based on the seventh digit
    if ($genderDigit < 5) {
        return 'Female';
    } else {
        return 'Male';
    }
}

$pdf->AliasNbPages();

$pdf->AddPage('L');

$header = [150, 160, 60, 30];
// Title
$pdf->SetFont('Arial', 'B', 20);

$pdf->Cell(1);
$pdf->Cell($header[0], 20, 'ATTENDANCE REGISTAR', "B", 1, 'L');
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell($header[0], 8, 'Booking No: ' . $booking['record_id'], "", 1, 'L');
$pdf->Cell($header[2], 8, 'Client: ' . $client['clients_name'], "", 1, 'L');
$pdf->Cell($header[2], 8, 'Assesor: ' . get_username($booking['safesure_users_id']), "", 1, 'L');
$pdf->Cell($header[2], 8, 'Status: ' . $booking['status'], "", 1, 'L');
$pdf->Cell($header[2], 8, 'Date Created: ' . $booking['date_booked'], "B", 0, 'L');
$pdf->Cell($header[2], 8, 'Date Approved: ' . $booking['date_approved'], "B", 0, 'L');
$pdf->Cell($header[3], 8, 'Date Done: ' . $booking['date_done'], "B", 1, 'L');
//          0   1   2   3   4   5   6   7   8   9  10  11
$header = [25, 25, 25, 21, 35, 25, 25, 35, 10, 15, 15, 21];
// Title

$pdf->SetFont('Arial', 'B', 8);

$explode_employee_ids = explode(",", $booking['client_employees']);
$explode_assesment_ids = explode(",", $booking['assesments']);
$explode_contracots_ids = explode(",", $booking['client_sites_id']);

$pdf->Cell(1);
$pdf->Cell($header[0], 8, 'Name: ', "B", 0, 'L');
$pdf->Cell($header[1], 8, 'Surname: ', "B", 0, 'L');
$pdf->Cell($header[2], 8, 'ID/passport: ', "B", 0, 'L');
// $pdf->Cell($header[3], 8, 'C.N.: ', "B", 0, 'L');
$pdf->Cell($header[4], 8, 'Occupation: ', "B", 0, 'L');
$pdf->Cell($header[7], 8, 'Employer:', "B", 0, 'L');
$pdf->Cell($header[7], 8, 'Contractor:', "B", 0, 'L');
// $pdf->Cell($header[6], 8, 'Badge Number ', "B", 0, 'L');
// $pdf->Cell($header[7], 8, 'Team Number ', "B", 0, 'L');
$pdf->Cell($header[8], 8, 'Age:', "B", 0, 'L');
$pdf->Cell($header[9], 8, 'Gender:', "B", 0, 'L');
$pdf->Cell($header[9], 8, 'Attended:', "B", 0, 'L');
$pdf->Cell($header[9], 8, 'Results:', "B", 0, 'L');
$pdf->Cell($header[10], 8, 'Attempts:', "B", 0, 'L');
$pdf->Cell($header[11], 8, 'Assesments:', "B", 1, 'L');
// loop though each employee
for ($i = 1; $i < (count($explode_employee_ids) - 1); $i++) {
    $pdf->SetFont('Arial', 'B', 6);

    $employee_res = $db->exec_query('client_employees', ['*'], '', '', '', '', "record_id = {$explode_employee_ids[$i]}");
    $employee = $employee_res->fetch_assoc();

    $asses_res = $db->exec_query('assesments', ['*'], '', '', '', '', "record_id = {$explode_assesment_ids[$i]}");
    $assesment = $asses_res->fetch_assoc();

    $contract_res = $db->exec_query('client_sites', ['*'], '', '', '', '', "record_id = {$explode_contracots_ids[$i]}");
    $contractor = $contract_res->fetch_assoc();

    $pdf->Cell(1);
    $pdf->Cell($header[0], 8, $employee['client_employees_name'], "B", 0, 'L');
    $pdf->Cell($header[1], 8, $employee['surname'], "B", 0, 'L');
    $pdf->Cell($header[2], 8, $employee['i_doc_passport'], "B", 0, 'L');
    // $pdf->Cell($header[3], 8, $employee['company_number'], "B", 0, 'L');
    $pdf->Cell($header[4], 8, $employee['occupation'], "B", 0, 'L');
    // $pdf->Cell($header[5], 8, $employee['teba_number'], "B", 0, 'L');
    // $pdf->Cell($header[6], 8, $employee['badge_number'], "B", 0, 'L');
    $pdf->Cell($header[7], 8, $client['clients_name'], "B", 0, 'L');
    $pdf->Cell($header[7], 8, $contractor['client_sites_name'], "B", 0, 'L');
    $pdf->Cell($header[8], 8, getAgeFromSAID($employee['i_doc_passport']), "B", 0, 'L');
    $pdf->Cell($header[9], 8, getGenderFromSAID($employee['i_doc_passport']), "B", 0, 'L');
    $result = $db->exec_query('asseses', ['*'], '', '', '', '', "booking = {$booking['record_id']} AND client_employees_id = {$employee['record_id']}", "ORDER BY record_id DESC");

    if ($result->num_rows > 0) {
        $pdf->Cell($header[10], 8, 'Yes ', "B", 0, 'L');
    } else {
        $pdf->Cell($header[10], 8, 'NO ', "B", 0, 'L');
    }
    $asses = $result->fetch_assoc();

    $pdf->Cell($header[9], 8, $asses['results'], "B", 0, 'L');
    $pdf->Cell($header[9], 8, $result->num_rows, "B", 0, 'L');

    $pdf->Cell($header[11], 8, $assesment['assesments_name'], "B", 1, 'L');


}


$pdf->Output("I");
