<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Credentials: true");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Date setup
date_default_timezone_set('Africa/Nairobi');

// Include database connection
include "../../../api/mobile_app/db_connection.php";

require "../fpdf.php";

// Handle both GET and POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Read JSON input for POST requests
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);

    // Extract parameters from JSON
    $technician = isset($data['technician']) ? $data['technician'] : null;
    $startDate = isset($data['startDate']) ? $data['startDate'] : null;
    $endDate = isset($data['endDate']) ? $data['endDate'] : null;
    $company_id = isset($data['company_id']) ? $data['company_id'] : null;
} else {
    // Extract parameters from GET request
    $technician = isset($_GET['technician']) ? $_GET['technician'] : null;
    $startDate = isset($_GET['startDate']) ? $_GET['startDate'] : null;
    $endDate = isset($_GET['endDate']) ? $_GET['endDate'] : null;
    $company_id = isset($_GET['company_id']) ? $_GET['company_id'] : null;
}

// Validate the input parameters
if (!$technician || !$startDate || !$endDate || !$company_id) {
    header('Content-Type: application/json');
    die(json_encode(['error' => 'Missing required parameters: technician, startDate, endDate, or company_id.']));
}

// Convert technician parameter to array
if (is_string($technician)) {
    $technician_ids = explode(',', $technician);
} elseif (is_array($technician)) {
    $technician_ids = $technician;
} else {
    $technician_ids = [];
}

$sql = "SELECT company_name FROM company WHERE company_id = '$company_id'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
$company_name = $row['company_name'];

//if ($company_name === 'Quavatel Ltd') {
  //      exit;
  //  }

class CustomPDF extends FPDF {
    function Header() {
        global $company_name, $startDate, $endDate;

        $this->SetFillColor(230, 230, 230);
        $this->Rect(0, 0, 297, 40, 'F'); // Wider rectangle for landscape

        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 10, strtoupper($company_name), 0, 1, 'C');

        $this->SetFont('Arial', '', 6);
        $this->Image('logo.png', 10, 5, 15); // Adjusted position for landscape

        $this->SetFont('Helvetica', 'B', 12);
        $this->Cell(0, 10, 'Technicians Performance Report', 0, 1, 'C');

        $this->SetFont('Times', '', 12);
        $this->Cell(0, 10, 'From ' . $startDate . ' To ' . $endDate, 0, 1, 'C');
        $this->Ln(10);
    }

    function Footer() {
        $this->SetY(-10);
        $this->SetFillColor(230, 230, 230);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(128, 128, 128);
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
        $this->Cell(0, 10, 'Powered by ckzgroup', 0, 0, 'R');
    }
}

// Create a new PDF instance with landscape orientation
$pdf = new CustomPDF('L'); // 'L' for landscape
$pdf->AliasNbPages();
$pdf->AddPage();

// Prepare the WHERE clause for technicians
if (in_array('ALL', $technician_ids)) {
    // Get all active technicians for the company
    $query = "SELECT CONCAT(Users.user_firstname, ' ', Users.user_lastname) AS username,
                     company.company_name AS company_name,
                     Users.user_contact AS technician_contact,
                     Users.user_email_address AS technician_email,
                     roles.role_name AS user_role,
                     Users.user_id AS user_id
              FROM Users
              INNER JOIN company ON Users.user_company_id = company.company_id
              INNER JOIN user_role ON user_role.user_id = Users.user_id
              INNER JOIN roles ON roles.role_id = user_role.role_id
              WHERE Users.user_company_id = '$company_id'
              AND roles.role_name = 'Technician'
              AND Users.user_account_status = 'Active'
              ORDER BY Users.user_firstname ASC";
} else {
    // Get only the specified technicians
    $tech_ids = implode("','", array_map('intval', $technician_ids));
    $query = "SELECT CONCAT(Users.user_firstname, ' ', Users.user_lastname) AS username,
                     company.company_name AS company_name,
                     Users.user_contact AS technician_contact,
                     Users.user_email_address AS technician_email,
                     roles.role_name AS user_role,
                     Users.user_id AS user_id
              FROM Users
              INNER JOIN company ON Users.user_company_id = company.company_id
              INNER JOIN user_role ON user_role.user_id = Users.user_id
              INNER JOIN roles ON roles.role_id = user_role.role_id
              WHERE Users.user_id IN ('$tech_ids')
              AND roles.role_name = 'Technician'
              ORDER BY Users.user_firstname ASC";
}

$result = mysqli_query($conn, $query);

$isFirstTechnician = true;

while ($rows = mysqli_fetch_assoc($result)) {

if (!$isFirstTechnician) {
        $pdf->AddPage();
    }
    $isFirstTechnician = false;

    $user_id = $rows['user_id'];
    $user_name = $rows['username'];
    $technician_email = $rows['technician_email'];
    $technician_contact = $rows['technician_contact'];
    $user_role = $rows['user_role'];

    // Technician details
    $pdf->Ln(10);
    $pdf->SetFont('Arial', 'BU', 16);
    $pdf->Cell(0, 10, 'Performance Report', 0, 0, 'C');
    $pdf->Ln(15);

    // Set styling
    $pdf->SetFillColor(240, 240, 240);
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(0, 10, 'Technician Details:', 0, 1, 'C', true);

    // Configuration
    $leftMargin = 15; // mm
    $rightMargin = 15; // mm
    $cellHeight = 10; // mm
    $fillColor = true;

    // First row: Name (left) and Role (right)
    $pdf->SetFont('Arial', 'B', 11);
    // Full-width background cell
    $pdf->Cell(0, $cellHeight, '', 0, 1, 'L', $fillColor);
    // Position for text
    $pdf->SetXY($leftMargin, $pdf->GetY() - $cellHeight);
    $pdf->Cell(0, $cellHeight, 'Name: ' . $user_name, 0, 0, 'L', false);
    $pdf->Cell(0, $cellHeight, 'Role: ' . $user_role, 0, 1, 'R', false);

    // Second row: Contact (left) and Email (right)
    // Full-width background cell
    $pdf->Cell(0, $cellHeight, '', 0, 1, 'L', $fillColor);
    // Position for text
    $pdf->SetXY($leftMargin, $pdf->GetY() - $cellHeight);
    $pdf->Cell(0, $cellHeight, 'Contact: ' . $technician_contact, 0, 0, 'L', false);
    $pdf->Cell(0, $cellHeight, 'Email: ' . $technician_email, 0, 1, 'R', false);

    $pdf->Ln(10);

    // Table header with adjusted widths for landscape
    $pdf->SetFont('Helvetica', 'B', 9);
    $pdf->Cell(70, 10, 'Service Name', 1, 0, 'C'); // Wider for service names
    $pdf->Cell(30, 10, 'Priority', 1, 0, 'C');
    $pdf->Cell(30, 10, 'SLA', 1, 0, 'C');
    $pdf->Cell(25, 10, 'Tickets', 1, 0, 'C');
    $pdf->Cell(35, 10, 'Tech Time Taken', 1, 0, 'C'); // Agent closure time
    $pdf->Cell(35, 10, 'AVG MTTR', 1, 0, 'C');      // NOC closure time
    $pdf->Cell(40, 10, 'SLA Compliance', 1, 1, 'C'); // Wider for percentage

    // Initialize totals
    $totalTimeTakenMinutes = 0;
    $totalMTTRMinutes = 0;
    $totalTickets = 0;

// Disable ONLY_FULL_GROUP_BY for this specific database connection session
    mysqli_query($conn, "SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''))");
    // Fetch ticket information
    $sql = "SELECT service_type.service_name AS Service_name,
                   priority.priority_level AS Priority,
                   ticket.ticket_id AS ticket_id,
                   CONCAT(sla.sla_time_hrs, 'h ', sla.sla_time_min, 'm') AS SLA,
                   COUNT(*) AS Total_Count,
                   ticket.ticket_service_type_id AS service_type_id,
                   sla.sla_time_hrs * 60 + sla.sla_time_min AS sla_total_minutes
            FROM ticket
            INNER JOIN ticket_assign ON ticket_assign.ticket_id = ticket.ticket_id
            INNER JOIN agent_closed_ticket ON agent_closed_ticket.ticket_id = ticket.ticket_id
            INNER JOIN noc_close_ticket ON noc_close_ticket.ticket_id = ticket.ticket_id
            INNER JOIN sla ON sla.sla_id = ticket.ticket_sla_id
            INNER JOIN service_type ON service_type.service_type_id = ticket.ticket_service_type_id
            INNER JOIN priority ON priority.priority_id = service_type.service_type_priority_id
            WHERE ticket_assign.agent_id = '$user_id'
            AND DATE(
                CASE
                    WHEN ticket.ticket_actual_time LIKE '%Z' THEN
                        STR_TO_DATE(SUBSTRING_INDEX(ticket.ticket_actual_time, '.', 1), '%Y-%m-%dT%H:%i:%s')
                    ELSE
                        STR_TO_DATE(ticket.ticket_actual_time, '%Y-%m-%d %h:%i:%s %p')
                END
            ) BETWEEN '$startDate' AND '$endDate'
            GROUP BY service_type.service_type_id";

    $ticketResult = mysqli_query($conn, $sql);

    if (mysqli_num_rows($ticketResult) > 0) {
        while ($ticket = mysqli_fetch_assoc($ticketResult)) {
            $service_type_id = $ticket['service_type_id'];
            $slaTotalMinutes = $ticket['sla_total_minutes'];
            $totalTickets += $ticket['Total_Count'];

            // Calculate Time Taken (agent closure time)
            $timeTakenSql = "SELECT
                            TIMESTAMPDIFF(
                                MINUTE,
                                CASE
                                    WHEN ticket.ticket_actual_time LIKE '%Z' THEN
                                        STR_TO_DATE(SUBSTRING_INDEX(ticket.ticket_actual_time, '.', 1), '%Y-%m-%dT%H:%i:%s')
                                    ELSE
                                        STR_TO_DATE(ticket.ticket_actual_time, '%Y-%m-%d %h:%i:%s %p')
                                END,
                                STR_TO_DATE(agent_closed_ticket.date_closed, '%Y-%m-%d %h:%i:%s %p')
                            ) AS minutes_diff
                            FROM ticket
                            INNER JOIN ticket_assign ON ticket_assign.ticket_id = ticket.ticket_id
                            INNER JOIN agent_closed_ticket ON agent_closed_ticket.ticket_id = ticket.ticket_id
                            WHERE ticket_assign.agent_id = '$user_id'
                            AND ticket.ticket_service_type_id = '$service_type_id'
                            AND DATE(
                                CASE
                                    WHEN ticket.ticket_actual_time LIKE '%Z' THEN
                                        STR_TO_DATE(SUBSTRING_INDEX(ticket.ticket_actual_time, '.', 1), '%Y-%m-%dT%H:%i:%s')
                                    ELSE
                                        STR_TO_DATE(ticket.ticket_actual_time, '%Y-%m-%d %h:%i:%s %p')
                                END
                            ) BETWEEN '$startDate' AND '$endDate'";

            $timeTakenQuery = mysqli_query($conn, $timeTakenSql);
            $timeTakenTotal = 0;
            $timeTakenCount = 0;

            while ($timeRow = mysqli_fetch_assoc($timeTakenQuery)) {
                $timeTakenTotal += $timeRow['minutes_diff'];
                $timeTakenCount++;
            }

            $totalTimeTakenMinutes += $timeTakenTotal;
            $avgTimeTaken = $timeTakenCount > 0 ? $timeTakenTotal / $timeTakenCount : 0;
            $timeTakenHours = floor($avgTimeTaken / 60);
            $timeTakenMins = floor($avgTimeTaken % 60);
            $timeTakenDisplay = ($timeTakenHours > 0 || $timeTakenMins > 0) ? $timeTakenHours . "h " . $timeTakenMins . "m" : "0h 0m";

            // Calculate MTTR (NOC closure time)
            $mttrSql = "SELECT
                        TIMESTAMPDIFF(
                            MINUTE,
                            CASE
                                WHEN ticket.ticket_actual_time LIKE '%Z' THEN
                                    STR_TO_DATE(SUBSTRING_INDEX(ticket.ticket_actual_time, '.', 1), '%Y-%m-%dT%H:%i:%s')
                                ELSE
                                    STR_TO_DATE(ticket.ticket_actual_time, '%Y-%m-%d %h:%i:%s %p')
                            END,
                            CASE
                                WHEN noc_close_ticket.noc_close_time LIKE '%Z' THEN
                                    STR_TO_DATE(SUBSTRING_INDEX(noc_close_ticket.noc_close_time, '.', 1), '%Y-%m-%dT%H:%i:%s')
                                ELSE
                                    STR_TO_DATE(noc_close_ticket.noc_close_time, '%Y-%m-%d %h:%i:%s %p')
                            END
                        ) AS minutes_diff
                        FROM ticket
                        INNER JOIN ticket_assign ON ticket_assign.ticket_id = ticket.ticket_id
                        INNER JOIN noc_close_ticket ON noc_close_ticket.ticket_id = ticket.ticket_id
                        WHERE ticket_assign.agent_id = '$user_id'
                        AND ticket.ticket_service_type_id = '$service_type_id'
                        AND DATE(
                            CASE
                                WHEN ticket.ticket_actual_time LIKE '%Z' THEN
                                    STR_TO_DATE(SUBSTRING_INDEX(ticket.ticket_actual_time, '.', 1), '%Y-%m-%dT%H:%i:%s')
                                ELSE
                                    STR_TO_DATE(ticket.ticket_actual_time, '%Y-%m-%d %h:%i:%s %p')
                            END
                        ) BETWEEN '$startDate' AND '$endDate'";

            $mttrQuery = mysqli_query($conn, $mttrSql);
            $mttrTotal = 0;
            $mttrCount = 0;
            $slaCompliantCount = 0;

            while ($mttrRow = mysqli_fetch_assoc($mttrQuery)) {
                $mttrTotal += $mttrRow['minutes_diff'];
                if ($mttrRow['minutes_diff'] <= $slaTotalMinutes) {
                    $slaCompliantCount++;
                }
                $mttrCount++;
            }

            $totalMTTRMinutes += $mttrTotal;
            $avgMTTR = $mttrCount > 0 ? $mttrTotal / $mttrCount : 0;
            $mttrHours = floor($avgMTTR / 60);
            $mttrMins = floor($avgMTTR % 60);
            $mttrDisplay = ($mttrHours > 0 || $mttrMins > 0) ? $mttrHours . "h " . $mttrMins . "m" : "0h 0m";

            // Calculate SLA compliance percentage (based on NOC closure time)
            $slaCompliance = $mttrCount > 0 ? round(($slaCompliantCount / $mttrCount) * 100, 2) : 0;
            $slaComplianceDisplay = $slaCompliance . "%";

            // Populate table row with adjusted widths
            $pdf->SetFont('Courier', '', 9);
            $pdf->Cell(70, 10, $ticket['Service_name'], 1, 0, 'C');
            $pdf->Cell(30, 10, $ticket['Priority'], 1, 0, 'C');
            $pdf->Cell(30, 10, $ticket['SLA'], 1, 0, 'C');
            $pdf->Cell(25, 10, $ticket['Total_Count'], 1, 0, 'C');
            $pdf->Cell(35, 10, $timeTakenDisplay, 1, 0, 'C');
            $pdf->Cell(35, 10, $mttrDisplay, 1, 0, 'C');
            $pdf->Cell(40, 10, $slaComplianceDisplay, 1, 1, 'C');
        }

        // Add summary row
        $pdf->SetFont('Helvetica', 'B', 9);
        $pdf->SetFillColor(220, 220, 220);

        // Convert total minutes to hours and minutes
        $totalTimeTakenHours = floor($totalTimeTakenMinutes / 60);
        $totalTimeTakenMins = $totalTimeTakenMinutes % 60;
        $totalTimeTakenDisplay = $totalTimeTakenHours . "h " . $totalTimeTakenMins . "m";

        $totalMTTRHours = floor($totalMTTRMinutes / 60);
        $totalMTTRMins = $totalMTTRMinutes % 60;
        $totalMTTRDisplay = $totalMTTRHours . "h " . $totalMTTRMins . "m";

        $pdf->Cell(70, 10, 'TOTAL', 1, 0, 'C', true);
        $pdf->Cell(30, 10, '', 1, 0, 'C', true);
        $pdf->Cell(30, 10, '', 1, 0, 'C', true);
        $pdf->Cell(25, 10, $totalTickets, 1, 0, 'C', true);
        $pdf->Cell(35, 10, $totalTimeTakenDisplay, 1, 0, 'C', true);
        $pdf->Cell(35, 10, $totalMTTRDisplay, 1, 0, 'C', true);
        $pdf->Cell(40, 10, '', 1, 1, 'C', true);
    } else {
        $pdf->SetFont('Courier', '', 9);
        $pdf->Cell(70, 10, 'N/A', 1, 0, 'C');
        $pdf->Cell(30, 10, 'N/A', 1, 0, 'C');
        $pdf->Cell(30, 10, 'N/A', 1, 0, 'C');
        $pdf->Cell(25, 10, '0', 1, 0, 'C');
        $pdf->Cell(35, 10, '0h 0m', 1, 0, 'C');
        $pdf->Cell(35, 10, '0h 0m', 1, 0, 'C');
        $pdf->Cell(40, 10, '0%', 1, 1, 'C');

        // Add empty summary row for consistency
        $pdf->SetFont('Helvetica', 'B', 9);
        $pdf->SetFillColor(220, 220, 220);
        $pdf->Cell(70, 10, 'TOTAL', 1, 0, 'C', true);
        $pdf->Cell(30, 10, '', 1, 0, 'C', true);
        $pdf->Cell(30, 10, '', 1, 0, 'C', true);
        $pdf->Cell(25, 10, '0', 1, 0, 'C', true);
        $pdf->Cell(35, 10, '0h 0m', 1, 0, 'C', true);
        $pdf->Cell(35, 10, '0h 0m', 1, 0, 'C', true);
        $pdf->Cell(40, 10, '', 1, 1, 'C', true);
    }

    $pdf->Ln(7);
}

// Output PDF
if (in_array('ALL', $technician_ids)) {
    $filename = 'Technicians_Performance_Report.pdf';
} else {
    if (count($technician_ids) > 1) {
        $filename = 'Multiple_Technicians_Performance_Report.pdf';
    } else {
        $filename = str_replace(' ', '_', ucwords($user_name)) . '_Performance_Report.pdf';
    }
}

// Clear cache headers
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// Force download
$pdf->Output('D', $filename);
?>
