<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__."/../config.php";
require_once __DIR__."/../mail/lettersMail.php";

header("Access-Control-Allow-Origin: * ");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header("Content-Type: text/plain");

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

if(sizeof($_POST) == 0) {
    $request_data = file_get_contents("php://input");
    $_POST = json_decode($request_data, true);
}

function fetchRenderedHTML($url, $cookies = null) {
    $ch = curl_init();
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
    ]);
    
    // If you need to pass session cookies
    if ($cookies) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookies);
    }
    
    $html = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL Error: " . $error);
    }
    
    curl_close($ch);
    
    if ($httpCode !== 200) {
        throw new Exception("HTTP Error: " . $httpCode);
    }
    
    return $html;
}

function cleanHTMLForPDF($html) {
    // Remove scripts that might interfere with PDF generation
    $html = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $html);
    
    // Remove the auto-print script specifically
    $html = str_replace('window.print();', '', $html);
    
    // Remove debug prevention scripts
    $html = preg_replace('/setInterval\s*\([^}]+debugger[^}]+\}\s*,\s*\d+\)\s*;?/is', '', $html);
    
    // Remove context menu prevention
    $html = str_replace('document.addEventListener("contextmenu", (event) => { event.preventDefault(); });', '', $html);
    
    // Remove key blocking scripts
    $html = preg_replace('/document\.addEventListener\s*\(\s*[\'"]keydown[\'"][^}]+\}\s*\)\s*;?/is', '', $html);
    
    return $html;
}

function generatePDFByContent($html, $output_dir, $filename_prefix) {
    try {
        // ####################################################### Write the HTML to a temporary file
        $temp_html_file = $output_dir . $filename_prefix . '.html';
        file_put_contents($temp_html_file, $html);
        // ####################################################### Write the HTML to a temporary file
        
        // ################################################### generate pdf from this html file
        $data = [
            'url' => "{$GLOBALS['url']}generated_pdf/{$filename_prefix}.html",
            "autoDelete" => true
        ];
        $ch = curl_init("https://scrap.digitalprominds.com/html-to-pdf/generate-pdf");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer c4417e69468fe116b829f8f5f1c716029e4d9041'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode != 200) {
            throw new Exception("Failed to generate PDF, HTTP code: " . $httpCode);
        }
        $response = json_decode($response, true);
        $file_path = $response['file'] ?? null;
        // ################################################### generate pdf from this html file


        // ################################################# download this file
        if ($file_path) {
            file_put_contents($output_dir . $filename_prefix . '.pdf', file_get_contents($file_path));
        }
        // ################################################# download this file


        // ####################################################### Clean up temporary HTML file
        if (file_exists($temp_html_file)) {
            unlink($temp_html_file);
        }
        // ####################################################### Clean up temporary HTML file

        return [
            'status' => 200,
            'pdf_url' => "{$GLOBALS['url']}generated_pdf/{$filename_prefix}.pdf",
            'pdf_local_path' => $output_dir . $filename_prefix . '.pdf',
            'message' => 'PDF generated successfully',
            // 'response' => $response,
            // 'data'=>$data
        ];
    } catch (Exception $e) {
        return [
            'status' => 500,
            'message' => 'PDF generation failed',
            'error' => "Error generating PDF: " . $e->getMessage()
        ];
    }
}


// Create output directory if it doesn't exist
function ensureOutputDirectory($path) {
    $directory = dirname($path);
    if (!is_dir($directory)) {
        if (!mkdir($directory, 0755, true)) {
            throw new Exception("Failed to create output directory: " . $directory);
        }
    }
    return $directory;
}





if(isset($_POST['letter_file_name'])) {
    $letter_file_name = $_POST['letter_file_name'];
    $letter_table = $_POST['letter_table'];
    $letter_id = $_POST['letter_id'];
    $id = base64_decode($letter_id);

    if($letter_table=='relieving_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, t2.employee_id FROM relieving_letter t1 INNER JOIN users t2 ON t2.employee_id=t1.employee_id WHERE t1.id='$id';"));
    }else if($letter_table=='internship_complete_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, t2.employee_id FROM internship_complete_letter t1 INNER JOIN users t2 ON t2.employee_id=t1.employee_id WHERE t1.id='$id';"));
    }else if($letter_table=='internship_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT 
            t2.name, t2.email, t3.designation_name AS position, t4.name AS mentor, t1.domain 
            FROM internship_letter t1 
            INNER JOIN users t2 ON t2.employee_id=t1.employee_id 
            INNER JOIN designations t3 ON t2.designation=t3.id 
            INNER JOIN users t4 ON t4.employee_id=t2.leader
            WHERE t1.id='$id';"));
    }else if($letter_table=='full_time_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT 
        t2.name, t2.email, t4.designation_name as position 
        FROM full_time_letter t1 
        INNER JOIN users t2 ON t2.employee_id=t1.employee_id 
        INNER JOIN designations t4 ON t4.id=t2.designation
        WHERE t1.id='$id';"));
    }else if($letter_table=='appraisal_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email FROM appraisal_letter t1 INNER JOIN users t2 ON t2.employee_id=t1.employee_id WHERE t1.id='$id';"));
    }

    $name = $result['name'] ?? 'Employee';
    $email = $result['email'] ?? '';
    // $email = 'iqbalshah9368@gmail.com';
    $employee_id = $result['employee_id'] ?? '';
    $position = $result['position'] ?? '';
    $domain = $result['domain'] ?? '';

    if(empty($email)) {
        echo json_encode([
            'status' => 500,
            'message' => 'Email not found for the employee.'
        ]);
        exit;
    }

    try {
        $letter_url = "{$url}letters/{$letter_file_name}?id={$letter_id}";
        $letter_html = fetchRenderedHTML($letter_url);
        $letter_html = cleanHTMLForPDF($letter_html);

        // Generate unique filename
        $safe_filename = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $letter_file_name);
        $unique_id = uniqid($safe_filename . '_', true);
        $timestamp = date('Ymd_His');
        $filename_prefix = $unique_id . '_' . $timestamp;
        
        // Ensure output directory exists
        $output_dir = __DIR__ . "/../generated_pdf/";
        ensureOutputDirectory($output_dir);
        // $output_path = $output_dir . $filename_prefix;
        

        $generation_data = generatePDFByContent($letter_html, $output_dir, $filename_prefix);
        if($generation_data['status']!=200) {
            echo json_encode([
                'status' => 500,
                'message' => $generation_data['message']
            ]);
            exit;
        }
        $pdf_local_path = $generation_data['pdf_local_path'] ?? null;
        $mail_status = send_letter([$name, $email, $employee_id, $letter_table, $pdf_local_path, $position, $domain]);

        if($mail_status == 1){
            mysqli_query($db, "UPDATE $letter_table SET mail_send='1' WHERE id='{$id}'");
    
            echo json_encode([
                'status' => 200,
                'message' => 'Mail Send successfully',
                'pdf_local_path' => $pdf_local_path,
                // 'filename_prefix' => $filename_prefix,
                // 'output_dir' => $output_dir,
                // 'generation_data' => $generation_data ? $generation_data : null
            ]);
        }else{
            echo json_encode([
                'status' => 500,
                'message' => 'Failed to send email',
                'error' => $mail_status
            ]);
            exit;
        }

    } catch (Exception $e) {
        echo json_encode([
            'status' => 500,
            'message' => 'PDF generation failed',
            'error' => 'Error generating PDF: ' . $e->getMessage()
        ]);
    }
}


if(isset($_POST['signed_attachment_id'])){

    $signed_attachment = $_FILES['signed_attachment'];
    $letter_table = $_POST['letter_table'];
    $letter_id = $_POST['letter_id'];
    $id = base64_decode($letter_id);

    // Check for upload errors
    if ($signed_attachment['error'] !== UPLOAD_ERR_OK) {
        echo json_encode([
            'status' => 500,
            'message' => 'Error uploading file.'
        ]);
        exit;
    }

    // Check file type
    $file_ext = strtolower(pathinfo($signed_attachment['name'], PATHINFO_EXTENSION));
    if ($file_ext !== 'pdf') {
        echo json_encode([
            'status' => 500,
            'message' => 'Signed attachment must be a PDF file.'
        ]);
        exit;
    }

    // Check file size (5 MB max)
    if ($signed_attachment['size'] > 5 * 1024 * 1024) {
        echo json_encode([
            'status' => 500,
            'message' => 'Signed attachment size exceeds 5 MB.'
        ]);
        exit;
    }

    // Generate safe and unique filename
    $safe_filename = preg_replace('/[^a-zA-Z0-9_\-]/', '_', 'signed_' . strtolower($letter_table) . '_' . $id);
    $unique_id = uniqid($safe_filename . '_', true);
    $timestamp = date('Ymd_His');
    $filename_prefix = $unique_id . '_' . $timestamp;
    $final_filename = $filename_prefix . '.' . $file_ext;

    // Ensure output directory exists
    $output_dir = __DIR__ . "/../generated_pdf/";
    ensureOutputDirectory($output_dir);

    // Final path
    $signed_attachment_path = $output_dir . $final_filename;
    // Move the uploaded file
    if (!move_uploaded_file($signed_attachment['tmp_name'], $signed_attachment_path)) {
        echo json_encode([
            'status' => 500,
            'message' => 'Failed to save signed attachment.'
        ]);
        exit;
    }

    // Save file path to DB (you may want to store just filename instead of full path)
    $escaped_path = mysqli_real_escape_string($db, $final_filename);

    $update_query = "UPDATE `$letter_table` SET signed_attachment='$escaped_path' WHERE id='$id'";
    if(!mysqli_query($db, $update_query)) {
        echo json_encode([
            'status' => 500,
            'message' => 'Failed to update signed attachment in database.',
            'error' => mysqli_error($db)
        ]);
        exit;
    }

    echo json_encode([
        'status' => 200,
        'message' => 'Signed attachment updated successfully',
        'signed_attachment_path' => "{$url}generated_pdf/{$final_filename}",
    ]);
    exit();
}


if(isset($_POST['signed_letter_file_name'])) {
    $letter_file_name = $_POST['signed_letter_file_name'];
    $letter_table = $_POST['signed_letter_table'];
    $letter_id = $_POST['signed_letter_id'];
    $id = base64_decode($letter_id);

    if($letter_table=='relieving_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, t2.employee_id, '' as signed_attachment FROM relieving_letter t1 INNER JOIN users t2 ON t2.employee_id=t1.employee_id WHERE t1.id='$id';"));
    }else if($letter_table=='internship_complete_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, t2.employee_id, '' as signed_attachment FROM internship_complete_letter t1 INNER JOIN users t2 ON t2.employee_id=t1.employee_id WHERE t1.id='$id';"));
    }else if($letter_table=='internship_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, t3.designation_name AS position, t1.domain, '' as signed_attachment 
        FROM internship_letter t1 
        INNER JOIN users t2 ON t2.employee_id=t1.employee_id 
        INNER JOIN designations t3 ON t2.designation=t3.id 
        INNER JOIN users t4 ON t4.employee_id=t2.leader
        WHERE t1.id='$id';"));
    }else if($letter_table=='full_time_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, t4.designation_name as position, signed_attachment 
        FROM full_time_letter t1 
        INNER JOIN users t2 ON t2.employee_id=t1.employee_id 
        INNER JOIN designations t4 ON t4.id=t2.designation
        WHERE t1.id='$id';"));
    }else if($letter_table=='appraisal_letter'){
        $result = mysqli_fetch_assoc(mysqli_query($db, "SELECT t2.name, t2.email, '' as signed_attachment FROM appraisal_letter t1 INNER JOIN users t2 ON t2.employee_id=t1.employee_id WHERE t1.id='$id';"));
    }

    $name = $result['name'] ?? 'Employee';
    $employee_id = $result['employee_id'] ?? '';
    $position = $result['position'] ?? '';
    $domain = $result['domain'] ?? '';

    $email = $result['email'] ?? '';
    // $email = 'iqbalshah9368@gmail.com';
    if(empty($email)) {
        echo json_encode([
            'status' => 500,
            'message' => 'Email not found for the employee.'
        ]);
        exit;
    }
    
    if(empty($result['signed_attachment'])) {
        echo json_encode([
            'status' => 500,
            'message' => 'Signed attachment not found for the letter.'
        ]);
        exit;
    }
    $output_dir = __DIR__ . "/../generated_pdf";
    $filename  = "{$result['signed_attachment']}";
    $pdf_local_path = $output_dir . "/{$result['signed_attachment']}";

    // check file exist or not 
    if(!file_exists($pdf_local_path)) {
        echo json_encode([
            'status' => 500,
            'message' => 'Signed attachment file does not exist.'
        ]);
        exit;
    }

       
    $mail_status = send_signed_letter([$name, $email, $employee_id, $letter_table, $pdf_local_path, $position, $domain]);
    if($mail_status == 1){
        mysqli_query($db, "UPDATE $letter_table SET signed_mail_send='1' WHERE id='{$id}'");

        echo json_encode([
            'status' => 200,
            'message' => 'Mail Send successfully',
            'pdf_local_path' => $pdf_local_path,
            // 'filename_prefix' => $filename_prefix,
            // 'output_dir' => $output_dir,
            // 'generation_data' => $generation_data ? $generation_data : null
        ]);
    }else{
        echo json_encode([
            'status' => 500,
            'message' => 'Failed to send email',
            'error' => $mail_status
        ]);
        exit;
    }
    
}

?>
