<?php
/* --------------------------------------------------------------
   generate_pdf.php  –  Employee PDF with guaranteed photo
   -------------------------------------------------------------- */
ob_start();                                   // MUST be first
error_reporting(E_ALL);
ini_set('display_errors', 0);                 // keep display off for production
ini_set('log_errors', 1);

// -------- CONFIG: adjust if needed --------
define('FPDF_PATH', __DIR__ . DIRECTORY_SEPARATOR . 'fpdf.php');   // path to fpdf.php
define('DEFAULT_PHOTO', __DIR__ . DIRECTORY_SEPARATOR . 'default-photo.jpg');
define('UPLOAD_DIR', rtrim(__DIR__, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'Uploads' . DIRECTORY_SEPARATOR);

// -------- check required files --------
if (!file_exists(FPDF_PATH)) {
    ob_end_clean();
    error_log("FPDF not found at " . FPDF_PATH);
    http_response_code(500);
    exit('Server configuration error: missing PDF library.');
}
require_once FPDF_PATH;

if (!file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'config.php')) {
    ob_end_clean();
    error_log("config.php not found");
    http_response_code(500);
    exit('Server configuration error: missing config.');
}
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php'; // should create $conn (mysqli)

/* -------- 1. GET & VALIDATE ID -------- */
$user_id = $_GET['id'] ?? '';
$user_id = trim($user_id);

if ($user_id === '') {
    ob_end_clean();
    http_response_code(400);
    exit('Missing ID parameter.');
}

/* allow IDs composed of letters, numbers, hyphen, underscore (adjust if your IDs differ) */
if (!preg_match('/^[A-Za-z0-9_\-]+$/', $user_id)) {
    ob_end_clean();
    http_response_code(400);
    exit('Invalid ID');
}

/* -------- 2. FETCH USER -------- */
$cols = [
    'id','first_name','last_name','email','role','reporting_manager','is_superadmin','status','resignation_date','rejoin_date',
    'basic_salary','responsibilities','role_id','mobileno','address','pancard','aadharcard','photo',
    'designation','division','marital_status','anniversary_date','gender','date_of_birth','date_of_joining',
    'mother_name','father_name','spouse_name','no_of_children','qualification','previous_experience',
    'company_name','last_company_1','last_company_1_years','last_company_1_salary','last_company_2',
    'last_company_2_years','last_company_2_salary','last_company_3','last_company_3_years','last_company_3_salary',
    'total_experience_years','previous_salary','uan_no','bloodgroup','esic_no','bank_name','account_number',
    'ifsc_code','level','performance','position','appointment_type','location','responsibilities_accepted','details_accepted'
];
$colsSql = implode(', ', $cols);

if (!($conn instanceof mysqli)) {
    ob_end_clean();
    error_log("DB connection (\$conn) is not a mysqli instance.");
    http_response_code(500);
    exit('Server configuration error: database connection.');
}

$stmt = $conn->prepare("SELECT $colsSql FROM users WHERE id = ?");
if (!$stmt) {
    ob_end_clean();
    error_log("DB prepare failed: " . $conn->error);
    http_response_code(500);
    exit('Database error (prepare).');
}

$stmt->bind_param('s', $user_id);
if (!$stmt->execute()) {
    $err = $stmt->error ?: $conn->error;
    $stmt->close();
    ob_end_clean();
    error_log("DB execute failed: " . $err);
    http_response_code(500);
    exit('Database error (execute).');
}

/* Try to fetch associative result (works when mysqlnd is available) */
$result = $stmt->get_result();
$user = false;
if ($result !== false) {
    $user = $result->fetch_assoc();
    $result->free();
} else {
    /* fallback: bind results manually */
    $bindNames = $cols;
    $bindTypes = [];
    $refs = [];
    foreach ($bindNames as $c) {
        $refs[] = null;
    }
    $bindParams = [];
    foreach ($bindNames as $i => $name) {
        $bindParams[] = &$refs[$i];
    }
    $meta = $stmt->result_metadata();
    if ($meta) {
        $stmt->bind_result(...$bindParams);
        if ($stmt->fetch()) {
            $user = [];
            foreach ($bindNames as $i => $name) {
                $user[$name] = $refs[$i];
            }
        }
        $meta->free();
    }
}
$stmt->close();

if (!$user) {
    ob_end_clean();
    http_response_code(404);
    exit('User not found');
}

/* -------- 3. PDF CLASS -------- */
class PDF extends FPDF {
    function Header() {
        $this->SetFont('Arial','B',16);
        $this->Cell(0,12,'Employee Details',0,1,'C');
        $this->Ln(6);
    }
    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial','I',8);
        $this->Cell(0,10,'Page '.$this->PageNo().' – '.date('d-m-Y'),0,0,'C');
    }
    function Section($txt) {
        $this->SetFont('Arial','B',12);
        $this->SetFillColor(240,240,240);
        $this->Cell(0,9,' '.$txt,0,1,'L',true);
        $this->Ln(2);
    }
    function Field($label,$value) {
        $this->SetFont('Arial','',10);
        $this->Cell(55,7,$label.':',0,0);
        $value = ($value === null || $value === '') ? 'N/A' : (string)$value;
        // sanitize simple text for PDF safety (FPDF will ignore HTML)
        $value = str_replace(array("\r","\n"), array(' ',' '), $value);
        if (strlen($value) > 80) {
            $this->MultiCell(0,7,$value);
            $this->Ln(1);
        } else {
            $this->Cell(0,7,$value,0,1);
        }
    }
}

/* -------- 4. PHOTO LOGIC -------- */
$defaultPhoto = DEFAULT_PHOTO;
$uploadDir = UPLOAD_DIR;
$photoPath = $defaultPhoto; // fallback

// normalize user-provided photo field
$photoFile = trim((string)($user['photo'] ?? ''));

if ($photoFile !== '') {
    // disallow directory traversal and ensure candidate is inside upload dir
    $candidate = realpath($uploadDir . $photoFile);
    if ($candidate !== false && strpos($candidate, realpath($uploadDir)) === 0 && is_file($candidate) && is_readable($candidate)) {
        $info = @getimagesize($candidate);
        if ($info !== false && in_array($info['mime'], ['image/jpeg','image/jpg','image/png'])) {
            $photoPath = $candidate;
            error_log("PHOTO OK for user {$user['id']}: $candidate");
        } else {
            error_log("PHOTO BAD FORMAT for user {$user['id']}: $candidate");
        }
    } else {
        error_log("PHOTO NOT FOUND or outside upload dir for user {$user['id']}: " . $uploadDir . $photoFile);
    }
} else {
    error_log("No photo set for user {$user['id']}, using default.");
}

/* if default missing, ensure we detect it */
if ($photoPath === $defaultPhoto && !file_exists($defaultPhoto)) {
    error_log("Default photo missing at $defaultPhoto. PDF will show NO IMAGE box.");
}

/* -------- 5. BUILD PDF -------- */
$pdf = new PDF();
$pdf->AddPage();
$pdf->SetAutoPageBreak(true,20);

/* ---- Photo Box (40×40 mm) ---- */
$photoX = 150;
$photoY = 30;
$photoW = 40;

if ($photoPath === $defaultPhoto && !file_exists($defaultPhoto)) {
    // default also missing → draw “NO IMAGE”
    $pdf->SetXY($photoX,$photoY);
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell($photoW,$photoW,'NO IMAGE',1,0,'C');
    $pdf->SetFont('Arial','',10);
} else {
    // wrap image embedding in try/catch equivalent: FPDF does not throw, but Image will output warning if invalid
    try {
        $pdf->Image($photoPath, $photoX, $photoY, $photoW, $photoW);
    } catch (Exception $e) {
        // fallback to NO IMAGE box
        $pdf->SetXY($photoX,$photoY);
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell($photoW,$photoW,'NO IMAGE',1,0,'C');
        $pdf->SetFont('Arial','',10);
        error_log("FPDF Image error: " . $e->getMessage());
    }
}

/* ---- Text area begins ---- */
$pdf->SetXY(10,30);

/* Personal */
$pdf->Section('Personal Information');
$pdf->Field('ID',               $user['id']);
$pdf->Field('First Name',       $user['first_name']);
$pdf->Field('Last Name',        $user['last_name']);
$pdf->Field('Gender',           $user['gender']);
$pdf->Field('Date of Birth',    $user['date_of_birth']);
$pdf->Field('Mother Name',      $user['mother_name']);
$pdf->Field('Father Name',      $user['father_name']);
$pdf->Field('Marital Status',   $user['marital_status']);
$pdf->Field('Spouse Name',      $user['spouse_name']);
$pdf->Field('Anniversary',      $user['anniversary_date']);
$pdf->Field('Children',         $user['no_of_children']);

/* Contact */
$pdf->Ln(4);
$pdf->Section('Contact Information');
$pdf->Field('Email',            $user['email']);
$pdf->Field('Mobile',           $user['mobileno']);
$pdf->Field('Address',          $user['address']);
$pdf->Field('PAN',              $user['pancard']);
$pdf->Field('Aadhar',           $user['aadharcard']);
$pdf->Field('Blood Group',      $user['bloodgroup']);

/* Employment */
$pdf->Ln(4);
$pdf->Section('Employment Details');
$pdf->Field('Division',         $user['division']);
$pdf->Field('Designation',      $user['designation']);
$pdf->Field('Level',            $user['level']);
$pdf->Field('Position',         $user['position']);
$pdf->Field('Appointment',      $user['appointment_type']);
$pdf->Field('Location',         $user['location']);
$pdf->Field('Joining Date',     $user['date_of_joining']);
$pdf->Field('Resignation',      $user['resignation_date']);
$pdf->Field('Status',           $user['status']);
$pdf->Field('Reporting Mgr',    $user['reporting_manager']);
$pdf->Field('Responsibilities', $user['responsibilities']);
$pdf->Field('Role ID',          $user['role_id']);

/* Financial */
$pdf->Ln(4);
$pdf->Section('Financial Details');
$pdf->Field('Basic Salary',     $user['basic_salary']);
$pdf->Field('Prev Salary',      $user['previous_salary']);
$pdf->Field('Bank',             $user['bank_name']);
$pdf->Field('A/c No',           $user['account_number']);
$pdf->Field('IFSC',             $user['ifsc_code']);
$pdf->Field('UAN',              $user['uan_no']);
$pdf->Field('ESIC',             $user['esic_no']);

/* Experience */
$pdf->Ln(4);
$pdf->Section('Experience Details');
$pdf->Field('Qualification',    $user['qualification']);
$pdf->Field('Prev Exp',         $user['previous_experience']);
$pdf->Field('Total Yrs',        $user['total_experience_years']);
$pdf->Field('Company',          $user['company_name']);
$pdf->Field('Last Co 1',        $user['last_company_1']);
$pdf->Field('Yrs 1',            $user['last_company_1_years']);
$pdf->Field('Sal 1',            $user['last_company_1_salary']);

/* Extra */
$pdf->Ln(4);
$pdf->Section('Additional');
$pdf->Field('Performance',      $user['performance']);

/* -------- 6. SEND PDF -------- */
ob_end_clean(); // important to clear any prior output

$filename = 'user_details_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', $user_id) . '.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');

$pdf->Output('D', $filename);
exit;
?>
