<?php
require("$_SERVER[DOCUMENT_ROOT]/fpdf.php");
include "$_SERVER[DOCUMENT_ROOT]/root.class.php";

$db = new db_safeguard();
$team_id = $_GET['team_id'];

// ✅ Get team members from the delimited column
$members_res = $db->query(
    "teams",
    "SELECT team_members FROM teams WHERE record_id='$team_id'"
);

$members = [];
$row = $members_res->fetch_assoc();

if ($row && !empty($row['team_members'])) {
    // ⚠️ Match the same delimiter used in team_members.ajax.php
    $members = array_filter(
        array_map('trim', explode(',', $row['team_members']))
    );
}

// Users for meters lookup — correct column
$users_res = $db->query("users", "SELECT record_id FROM users WHERE team_id='$team_id'");

// Get completed jobcards count
$jobcards_res = $db->query("jobcards", "SELECT COUNT(*) as total FROM jobcards WHERE team_assigned_id='$team_id' AND status=1");
$jobcards_total = $jobcards_res->fetch_assoc()['total'];

$users_res = $db->query("users", "SELECT * FROM users WHERE record_id='$team_id'");
$user_ids = [];
while ($u = $users_res->fetch_assoc())
    $user_ids[] = $u['record_id'];

$user_ids_sql = "'" . implode("','", $user_ids) . "'";

// Get meters breakdown
$meters_res = $db->query("jobcard_timeline", "
    SELECT type, SUM(meters) as total
    FROM jobcard_timeline
    WHERE user_id IN ($user_ids_sql)
    GROUP BY type
");

$meters = [
    "reim" => 0,
    "drill" => 0,
    "casing" => 0,
    "blasting" => 0
];

while ($row = $meters_res->fetch_assoc()) {
    $t = strtolower($row['type']);
    $meters[$t] = $row['total'];
}

// Get jobcard durations
// $users_res = $db->query("users", "SELECT * FROM users WHERE record_id='$team_id'");
// $user_ids = [];
// while ($u = $users_res->fetch_assoc())
//     $user_ids[] = $u['record_id'];

// $user_ids_sql = "'" . implode("','", $user_ids) . "'";

// $duration_res = $db->query("jobcard_timeline", "
//     SELECT jobcard_id, ROUND(TIMESTAMPDIFF(MINUTE, MIN(date_time), MAX(date_time)) / 60,2) as hours
//     FROM jobcard_timeline
//     WHERE user_id IN ($user_ids_sql)
//     GROUP BY jobcard_id
// ");

// $durations = [];
// while ($row = $duration_res->fetch_assoc()) {
//     $durations[] = "Jobcard " . $row['jobcard_id'] . " : " . $row['hours'] . " hrs";
// }

class PDF extends FPDF
{
    function SectionTitle($title)
    {
        $this->SetFont('Arial', 'B', 14);
        $this->SetFillColor(230, 126, 34); // Orange
        $this->SetTextColor(255, 255, 255);
        $this->Cell(0, 10, $title, 0, 1, 'L', true);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(3);
    }
    function InfoRow($label, $value, $fullWidth = false)
    {
        $this->SetFont('Arial', 'B', 10);
        $this->SetTextColor(41, 128, 185); // Blue for labels

        if ($fullWidth) {
            $this->Cell(0, 7, $label . ':', 0, 1, 'L');
            $this->SetFont('Arial', '', 10);
            $this->SetTextColor(0, 0, 0);
            $this->MultiCell(0, 6, $value ?: 'N/A', 0, 'L');
        } else {
            $this->Cell(55, 7, $label . ':', 0, 0, 'L');
            $this->SetFont('Arial', '', 10);
            $this->SetTextColor(0, 0, 0);
            $this->Cell(0, 7, $value ?: 'N/A', 0, 1, 'L');
        }
        $this->SetTextColor(0, 0, 0);
    }

    function TableHeader($headers, $widths)
    {
        $this->SetFont('Arial', 'B', 10);
        $this->SetFillColor(52, 152, 219); // Blue for table headers
        $this->SetTextColor(255, 255, 255);
        $this->SetDrawColor(41, 128, 185); // Blue border
        $this->SetLineWidth(0.3);

        foreach ($headers as $i => $header) {
            $this->Cell($widths[$i], 8, $header, 1, 0, 'C', true);
        }
        $this->Ln();
        $this->SetTextColor(0, 0, 0);
    }

    function TableRow($data, $widths, $fill = false)
    {
        $this->SetFont('Arial', '', 9);
        $fillColor = $fill ? array(236, 240, 241) : array(255, 255, 255);
        $this->SetFillColor($fillColor[0], $fillColor[1], $fillColor[2]);
        $this->SetDrawColor(189, 195, 199);

        foreach ($data as $i => $cell) {
            $this->Cell($widths[$i], 7, $cell, 1, 0, 'L', true);
        }
        $this->Ln();
    }


}
// Create PDF
$pdf = new FPDF();
$pdf->AddPage();

// Header
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 10, "Team Report: $team_name", 0, 1, 'C');
$pdf->Ln(5);

// Team Members
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, "Team Members:", 0, 1);
$pdf->SetFont('Arial', '', 12);
foreach ($members as $member) {
    $pdf->Cell(0, 6, "- $member", 0, 1);
}
$pdf->Ln(5);

// Completed Jobcards
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, "Completed Jobcards: $jobcards_total", 0, 1);
$pdf->Ln(5);

// Meters Breakdown
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 8, "Meters Breakdown:", 0, 1);
$pdf->SetFont('Arial', '', 12);
foreach ($meters as $type => $value) {
    $pdf->Cell(0, 6, "- " . ucfirst($type) . " : $value meters", 0, 1);
}
$pdf->Ln(5);

// Jobcard durations
// $pdf->SetFont('Arial', 'B', 12);
// $pdf->Cell(0, 8, "Jobcard Durations:", 0, 1);
// $pdf->SetFont('Arial', '', 12);
// foreach ($durations as $d) {
//     $pdf->Cell(0, 6, "- $d", 0, 1);
// }

// Output PDF
$pdf->Output("I", "Team_Report_{$team_name}.pdf");
