<?php
// admin/feedback-pdf.php - Professional PDF Report
require_once '../config/config.php';
require_once('../tcpdf/tcpdf.php');

require_login();

$feedback_id = $_GET['id'] ?? 0;

if (!$feedback_id) {
    die('Invalid feedback ID');
}

// Fetch feedback details
$stmt = $pdo->prepare("
    SELECT 
        f.id as feedback_id,
        f.training_id,
        f.student_name,
        f.email,
        f.job_role,
        f.company_name,
        f.ratings_json,
        f.question_json,
        f.submitted_at,
        t.course_name,
        t.instructor_name,
        t.client_name,
        t.course_date,
        t.course_venue
    FROM tm_feedback f
    LEFT JOIN tm_training t ON f.training_id = t.id
    WHERE f.id = ?
");
$stmt->execute([$feedback_id]);
$feedback = $stmt->fetch();

if (!$feedback) {
    die('Feedback not found');
}

$ratings = json_decode($feedback->ratings_json, true);
$questions = json_decode($feedback->question_json, true);

// Define rating categories
$rating_categories = [
    'Instructor Evaluation' => [
        'color' => [52, 152, 219],
        'questions' => [
            'instructor_knowledge' => 'Instructor\'s knowledge of the subject matter',
            'instructor_response' => 'Instructor\'s response to questions',
            'instructor_relevance' => 'Instructor\'s ability to provide real world examples',
            'instructor_delivery' => 'Instructor\'s presentation skills',
            'instructor_overall' => 'Instructor\'s overall performance'
        ]
    ],
    'Training Content' => [
        'color' => [155, 89, 182],
        'questions' => [
            'content_clarity' => 'Clarity of the training content',
            'content_flow' => 'Flow of the training content',
            'content_depth' => 'Depth of the training content',
            'content_effectiveness' => 'Effectiveness of the exercises in knowledge/skills learned',
            'content_relevance' => 'Relevance of the exercises to real world situations',
            'content_time' => 'Time dedicated to discussions and practices'
        ]
    ],
    'Learning Effectiveness' => [
        'color' => [46, 204, 113],
        'questions' => [
            'learning_gained' => 'Knowledge and skills gained from this training',
            'learning_impact' => 'Impact of this training on your productivity related to the subject',
            'overall_rating' => 'How do you rate the training overall?'
        ]
    ]
];

$objective_questions = [
    'objective_solve' => 'Solve a particular problem',
    'objective_prepare_deploy' => 'Prepare for a new product deployment or software upgrade',
    'objective_cert' => 'Prepare for certification exam',
    'objective_build' => 'Build new skills and knowledge'
];

$open_ended_questions = [
    'open_suggestions' => 'Suggestions for improving the course or Overall Training Experience?',
    'open_future_topics' => 'Are there any additional training topics or courses you would be interested in attending in the future?',
    'open_objectives_others' => 'Others (Please specify)'
];

// Calculate averages
$rating_values = [];
foreach ($rating_categories as $categoryData) {
    foreach ($categoryData['questions'] as $key => $label) {
        if (isset($ratings[$key]) && is_numeric($ratings[$key])) {
            $rating_values[] = $ratings[$key];
        }
    }
}
$avg_rating = !empty($rating_values) ? array_sum($rating_values) / count($rating_values) : 0;

// Create PDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Time Training Center');
$pdf->SetAuthor('Time Training Center');
$pdf->SetTitle('Training Feedback Report');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(15, 15, 15);
$pdf->SetAutoPageBreak(TRUE, 15);
$pdf->AddPage();

// ==================== WHITE HEADER WITH LOGO ====================
// White background
$pdf->SetFillColor(255, 255, 255);
$pdf->Rect(0, 0, 210, 55, 'F');

// Download logo
$logoUrl = 'https://www.timetraining.ae/design/images/new_logo.png';
$logoDisplayed = false;

try {
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ]);
    
    $logoData = @file_get_contents($logoUrl, false, $context);
    
    if ($logoData !== false && strlen($logoData) > 0) {
        $tempLogo = sys_get_temp_dir() . '/ttc_logo_' . time() . '.png';
        file_put_contents($tempLogo, $logoData);
        
        if (file_exists($tempLogo) && filesize($tempLogo) > 0) {
            // Logo centered: (210 - 70) / 2 = 70
            $pdf->Image($tempLogo, 70, 10, 70, 0, 'PNG', '', '', false, 300, '', false, false, 0);
            $logoDisplayed = true;
            
            // Clean up temp file
            @unlink($tempLogo);
        }
    }
} catch (Exception $e) {
    $logoDisplayed = false;
}

// Fallback text logo if image fails
if (!$logoDisplayed) {
    $pdf->SetFont('helvetica', 'B', 16);
    $pdf->SetTextColor(0, 75, 117);
    $pdf->SetXY(15, 18);
    $pdf->Cell(180, 10, 'TIME TRAINING CENTER', 0, 1, 'C');
    
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetXY(15, 28);
    $pdf->Cell(180, 6, 'Abu Dhabi, UAE', 0, 1, 'C');
}

// Tagline
$pdf->SetFont('helvetica', '', 8);
$pdf->SetTextColor(100, 100, 100);
$pdf->SetXY(15, 38);
$pdf->Cell(180, 4, 'Professional Training & Development Excellence', 0, 1, 'C');

$pdf->SetFont('helvetica', 'B', 8);
$pdf->SetXY(15, 43);
$pdf->Cell(180, 4, 'Abu Dhabi, UAE  |  Over 32 Years of Training Excellence', 0, 1, 'C');

// Gold accent bar
$pdf->SetFillColor(1, 129, 190); // #0181be
$pdf->Rect(0, 55, 210, 3, 'F');

// Report title
$pdf->SetY(63);
$pdf->SetFont('helvetica', 'B', 20);
$pdf->SetTextColor(0, 75, 117);
$pdf->Cell(0, 8, 'Training Feedback Report', 0, 1, 'C');

$pdf->SetFont('helvetica', '', 8);
$pdf->SetTextColor(120, 120, 120);
$pdf->Cell(0, 4, 'Generated: ' . date('l, F d, Y - h:i A'), 0, 1, 'C');

$pdf->Ln(3);

// ==================== OVERALL SCORE ====================
$scoreY = $pdf->GetY();

$pdf->SetFillColor(255, 255, 255);
$pdf->SetDrawColor(220, 220, 220);
$pdf->SetLineWidth(0.5);
$pdf->RoundedRect(15, $scoreY, 180, 32, 3, '1111', 'DF');

$pdf->SetFillColor(0, 75, 117);
$pdf->Rect(15, $scoreY, 4, 32, 'F');

// Left - Score
$pdf->SetFont('helvetica', 'B', 36);
$pdf->SetTextColor(0, 75, 117);
$pdf->SetXY(25, $scoreY + 6);
$pdf->Cell(50, 12, number_format($avg_rating, 1), 0, 0, 'C');

$pdf->SetFont('helvetica', '', 9);
$pdf->SetTextColor(120, 120, 120);
$pdf->SetXY(25, $scoreY + 20);
$pdf->Cell(50, 5, 'out of 5.0', 0, 1, 'C');

// Divider
$pdf->SetDrawColor(230, 230, 230);
$pdf->Line(80, $scoreY + 5, 80, $scoreY + 27);

// Right - Stars
$pdf->SetFont('dejavusans', '', 16);
$pdf->SetTextColor(255, 193, 7);
$stars = '';
for ($i = 1; $i <= 5; $i++) {
    $stars .= $i <= round($avg_rating) ? '★' : '☆';
}
$pdf->SetXY(85, $scoreY + 6);
$pdf->Cell(105, 8, $stars, 0, 1, 'C');

// Performance badge
if ($avg_rating >= 4.5) {
    $pdf->SetFillColor(46, 204, 113);
    $performance = 'EXCELLENT';
} elseif ($avg_rating >= 4.0) {
    $pdf->SetFillColor(52, 152, 219);
    $performance = 'VERY GOOD';
} elseif ($avg_rating >= 3.5) {
    $pdf->SetFillColor(241, 196, 15);
    $performance = 'GOOD';
} elseif ($avg_rating >= 3.0) {
    $pdf->SetFillColor(230, 126, 34);
    $performance = 'SATISFACTORY';
} else {
    $pdf->SetFillColor(231, 76, 60);
    $performance = 'NEEDS IMPROVEMENT';
}

$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetTextColor(255, 255, 255);
$pdf->RoundedRect(110, $scoreY + 18, 60, 8, 2, '1111', 'F');
$pdf->SetXY(110, $scoreY + 19);
$pdf->Cell(60, 6, $performance, 0, 1, 'C');

$pdf->SetY($scoreY + 35);

// ==================== INFO CARDS ====================
$cardY = $pdf->GetY();

// Participant card
$pdf->SetFillColor(255, 255, 255);
$pdf->SetDrawColor(220, 220, 220);
$pdf->RoundedRect(15, $cardY, 87, 48, 3, '1111', 'DF');

$pdf->SetFillColor(245, 248, 251);
$pdf->RoundedRect(15, $cardY, 87, 10, 3, '1111', 'F');

$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetTextColor(0, 75, 117);
$pdf->SetXY(20, $cardY + 3);
$pdf->Cell(0, 4, 'PARTICIPANT DETAILS', 0, 1);

$infoItems = [
    ['Name', htmlspecialchars($feedback->student_name)],
    ['Role', htmlspecialchars($feedback->job_role)],
    ['Company', htmlspecialchars($feedback->company_name)],
    ['Submitted', date('M d, Y - h:i A', strtotime($feedback->submitted_at))]
];

$infoY = $cardY + 13;
foreach ($infoItems as $item) {
    $pdf->SetXY(20, $infoY);
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetTextColor(120, 120, 120);
    $pdf->Cell(0, 4, strtoupper($item[0]), 0, 1);
    
    $pdf->SetXY(20, $infoY + 3.5);
    $pdf->SetFont('helvetica', '', 8);
    $pdf->SetTextColor(40, 40, 40);
    $pdf->Cell(0, 4, $item[1], 0, 1);
    $infoY += 9;
}

// Training card
$pdf->SetFillColor(255, 255, 255);
$pdf->SetDrawColor(220, 220, 220);
$pdf->RoundedRect(108, $cardY, 87, 48, 3, '1111', 'DF');

$pdf->SetFillColor(245, 248, 251);
$pdf->RoundedRect(108, $cardY, 87, 10, 3, '1111', 'F');

$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetTextColor(0, 75, 117);
$pdf->SetXY(113, $cardY + 3);
$pdf->Cell(0, 4, 'TRAINING DETAILS', 0, 1);

$trainingItems = [
    ['Course', htmlspecialchars($feedback->course_name)],
    ['Instructor', htmlspecialchars($feedback->instructor_name)],
    ['Client', htmlspecialchars($feedback->client_name)],
    ['Venue', htmlspecialchars($feedback->course_venue)]
];

$trainingY = $cardY + 13;
foreach ($trainingItems as $item) {
    $pdf->SetXY(113, $trainingY);
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->SetTextColor(120, 120, 120);
    $pdf->Cell(0, 4, strtoupper($item[0]), 0, 1);
    
    $pdf->SetXY(113, $trainingY + 3.5);
    $pdf->SetFont('helvetica', '', 8);
    $pdf->SetTextColor(40, 40, 40);
    $pdf->MultiCell(77, 4, $item[1], 0, 'L');
    $trainingY += 9;
}

// ==================== DETAILED RATINGS ====================
$pdf->SetY($cardY + 52);

foreach ($rating_categories as $categoryName => $categoryData) {
    if ($pdf->GetY() > 230) {
        $pdf->AddPage();
        $pdf->SetY(20);
    }
    
    $catColor = $categoryData['color'];
    $catY = $pdf->GetY();
    
    // Category header
    $pdf->SetFillColor($catColor[0], $catColor[1], $catColor[2]);
    $pdf->RoundedRect(15, $catY, 180, 10, 2, '1111', 'F');
    
    $pdf->SetFont('helvetica', 'B', 11);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetXY(20, $catY + 2.5);
    $pdf->Cell(0, 5, strtoupper($categoryName), 0, 1, 'L');
    
    $pdf->SetY($catY + 12);
    
    // Category average - FIXED
    $categoryValues = [];
    foreach ($categoryData['questions'] as $key => $label) {
        if (isset($ratings[$key]) && is_numeric($ratings[$key])) {
            $categoryValues[] = $ratings[$key];
        }
    }
    $categoryAvg = !empty($categoryValues) ? array_sum($categoryValues) / count($categoryValues) : 0;
    
    $avgY = $pdf->GetY();
    $pdf->SetFillColor(248, 250, 252);
    $pdf->RoundedRect(15, $avgY, 180, 8, 2, '1111', 'F');
    
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetTextColor(60, 60, 60);
    $pdf->SetXY(20, $avgY + 2);
    $pdf->Cell(70, 4, 'Category Average:', 0, 0, 'L');
    
    $pdf->SetFont('dejavusans', '', 9);
    $pdf->SetTextColor(255, 193, 7);
    $catStars = '';
    for ($i = 1; $i <= 5; $i++) {
        $catStars .= $i <= round($categoryAvg) ? '★' : '☆';
    }
    $pdf->SetXY(95, $avgY + 2);
    $pdf->Cell(60, 4, $catStars, 0, 0, 'C');
    
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->SetTextColor($catColor[0], $catColor[1], $catColor[2]);
    $pdf->SetXY(160, $avgY + 2);
    $pdf->Cell(30, 4, number_format($categoryAvg, 1) . '/5.0', 0, 1, 'R');
    
    $pdf->SetY($avgY + 11);
    
    // Questions
    foreach ($categoryData['questions'] as $key => $label) {
        if (isset($ratings[$key]) && is_numeric($ratings[$key])) {
            $value = $ratings[$key];
            
            if ($pdf->GetY() > 255) {
                $pdf->AddPage();
                $pdf->SetY(20);
            }
            
            $qY = $pdf->GetY();
            
            $pdf->SetFillColor(255, 255, 255);
            $pdf->SetDrawColor(240, 240, 240);
            $pdf->SetLineWidth(0.3);
            $pdf->RoundedRect(15, $qY, 180, 15, 2, '1111', 'DF');
            
            // Question text
            $pdf->SetFont('helvetica', '', 8);
            $pdf->SetTextColor(60, 60, 60);
            $pdf->SetXY(20, $qY + 2.5);
            $pdf->Cell(110, 4, $label, 0, 1, 'L');
            
            // Progress bar
            $barY = $qY + 8;
            $pdf->SetFillColor(235, 235, 235);
            $pdf->RoundedRect(20, $barY, 105, 4, 1, '1111', 'F');
            
            $barWidth = ($value / 5) * 105;
            $pdf->SetFillColor($catColor[0], $catColor[1], $catColor[2]);
            $pdf->RoundedRect(20, $barY, $barWidth, 4, 1, '1111', 'F');
            
            // Stars
            $pdf->SetFont('dejavusans', '', 8);
            $pdf->SetTextColor(255, 193, 7);
            $starStr = '';
            for ($i = 1; $i <= 5; $i++) {
                $starStr .= $i <= $value ? '★' : '☆';
            }
            $pdf->SetXY(130, $qY + 3.5);
            $pdf->Cell(35, 4, $starStr, 0, 0, 'C');
            
            // Score circle
            $pdf->SetFillColor($catColor[0], $catColor[1], $catColor[2]);
            $pdf->Circle(180, $qY + 7.5, 5, 0, 360, 'F');
            
            $pdf->SetFont('helvetica', 'B', 9);
            $pdf->SetTextColor(255, 255, 255);
            $pdf->SetXY(175, $qY + 5);
            $pdf->Cell(10, 5, $value, 0, 0, 'C');
            
            $pdf->SetY($qY + 16.5);
        }
    }
    
    $pdf->SetY($pdf->GetY() + 3);
}

// ==================== OBJECTIVES ====================
$selectedObjectives = [];
foreach ($objective_questions as $key => $label) {
    if (isset($ratings[$key]) && $ratings[$key] == '1') {
        $selectedObjectives[] = $label;
    }
}

if (!empty($selectedObjectives)) {
    if ($pdf->GetY() > 240) {
        $pdf->AddPage();
        $pdf->SetY(20);
    }
    
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetTextColor(0, 75, 117);
    $pdf->Cell(0, 6, 'PRE-TRAINING OBJECTIVES', 0, 1);
    
    $pdf->SetFont('helvetica', '', 8);
    $pdf->SetTextColor(60, 60, 60);
    
    foreach ($selectedObjectives as $objective) {
        $pdf->SetX(20);
        $pdf->Cell(3, 5, chr(149), 0, 0);
        $pdf->Cell(0, 5, $objective, 0, 1);
    }
    
    $pdf->Ln(3);
}

// ==================== FEEDBACK ====================
$textResponses = [];
foreach ($open_ended_questions as $key => $label) {
    if ($key === 'open_objectives_others') continue;
    if (isset($ratings[$key]) && !empty(trim($ratings[$key])) && $ratings[$key] !== 'N/A') {
        $textResponses[$key] = ['label' => $label, 'answer' => $ratings[$key]];
    }
}

if (!empty($textResponses)) {
    if ($pdf->GetY() > 220) {
        $pdf->AddPage();
        $pdf->SetY(20);
    }
    
    $pdf->SetFont('helvetica', 'B', 11);
    $pdf->SetTextColor(0, 75, 117);
    $pdf->Cell(0, 8, 'ADDITIONAL FEEDBACK & SUGGESTIONS', 0, 1);
    
    $pdf->Ln(2);
    
    foreach ($textResponses as $data) {
        if ($pdf->GetY() > 240) {
            $pdf->AddPage();
            $pdf->SetY(20);
        }
        
        $feedY = $pdf->GetY();
        
        // Question header
        $pdf->SetFillColor(0, 75, 117);
        $pdf->RoundedRect(15, $feedY, 180, 7, 2, '1111', 'F');
        
        $pdf->SetFont('helvetica', 'B', 8);
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetXY(20, $feedY + 2);
        $pdf->Cell(0, 3, $data['label'], 0, 1);
        
        // Answer
        $pdf->SetY($feedY + 9);
        $answerText = htmlspecialchars($data['answer']);
        
        $pdf->SetFillColor(248, 250, 252);
        $pdf->SetFont('helvetica', '', 8);
        $pdf->SetTextColor(50, 50, 50);
        
        $answerHeight = $pdf->getStringHeight(170, $answerText);
        $pdf->RoundedRect(15, $pdf->GetY(), 180, $answerHeight + 4, 2, '1111', 'F');
        
        $pdf->SetXY(20, $pdf->GetY() + 2);
        $pdf->MultiCell(170, 4, $answerText, 0, 'L');
        
        $pdf->SetY($pdf->GetY() + 5);
    }
}

// ==================== FOOTER ====================
$pdf->SetY(-15);
$pdf->SetFont('helvetica', '', 7);
$pdf->SetTextColor(150, 150, 150);
$pdf->Cell(0, 4, 'Time Training Center | Abu Dhabi, UAE | www.timetraining.ae', 0, 1, 'C');
$pdf->SetFont('helvetica', 'I', 6);
$pdf->Cell(0, 3, 'Confidential Document - For Internal Use Only', 0, 1, 'C');

// Output
$filename = 'Feedback_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', $feedback->student_name) . '_' . date('Ymd') . '.pdf';
if (ob_get_contents()) ob_end_clean();
$pdf->Output($filename, 'D');
exit;
?>