<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available.

$status_message = '';
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 for safety
$generated_content = null;

// --- Fixed Letterpad Components ---
$company_name = "CyberLog";
$company_address = "1/6, Block: New-C, Mirpur-1, Dhaka-12169";
$company_email = "info@cyberlog.com.bd";
$company_website = "www.cyberlog.com.bd";

// --- Function to build the Letterhead and Footer HTML ---
function get_letterhead_html($title) {
    global $company_name, $company_address, $company_email, $company_website;
    return "
        <header style='border-bottom: 3px solid #3498db; padding-bottom: 10px; margin-bottom: 30px; text-align: center;'>
            <h1 style='color: #3498db; margin: 0; font-size: 24px;'>{$company_name}</h1>
            <p style='margin: 5px 0 0 0; font-size: 12px; color: #555;'>{$company_address}</p>
            <p style='margin: 0; font-size: 12px; color: #555;'>Email: {$company_email} | Web: {$company_website}</p>
        </header>
        <h2 style='text-align: center; color: #2c3e50; border-bottom: 1px dashed #ccc; padding-bottom: 10px;'>{$title}</h2>
    ";
}

function get_letter_footer_html() {
    global $company_name;
    return "
        <footer style='margin-top: 60px; padding-top: 10px; border-top: 1px solid #ccc; font-size: 10px; text-align: center; color: #7f8c8d; position: absolute; bottom: 0; width: 100%;'>
            <p>&copy; " . date('Y') . " {$company_name}. All Rights Reserved.</p>
        </footer>
    ";
}


// --- Logic to Handle Form Submission (Generate & Save) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_letter'])) {
    
    // 1. Sanitize Inputs
    $doc_title = $conn->real_escape_string($_POST['document_title'] ?? 'General Letter');
    $letter_date = $conn->real_escape_string($_POST['letter_date'] ?? date('Y-m-d'));
    $recipient = $conn->real_escape_string($_POST['recipient_details'] ?? '');
    $body = $conn->real_escape_string($_POST['body_content'] ?? '');

    // 2. Save to Database
    $sql_insert = "INSERT INTO company_letterpads (document_title, letter_date, recipient_details, body_content, created_by) 
                   VALUES (?, ?, ?, ?, ?)";
    
    if ($stmt = $conn->prepare($sql_insert)) {
        $stmt->bind_param("ssssi", $doc_title, $letter_date, $recipient, $body, $user_id);
        
        if ($stmt->execute()) {
            $last_id = $stmt->insert_id;
            $status_message = "<div class='alert alert-success'>Company Letterpad Document (ID: {$last_id}) generated and saved successfully!</div>";
        } else {
            $status_message = "<div class='alert alert-error'>Database error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        $status_message = "<div class='alert alert-error'>Database preparation error: " . $conn->error . "</div>";
    }

    // 3. Generate HTML Content for the Draft Viewer
    $head = get_letterhead_html(htmlspecialchars($doc_title));
    $foot = get_letter_footer_html();
    
    // Format body content for viewing (replacing newlines with <br>)
    $formatted_body = nl2br(htmlspecialchars($body)); 
    $formatted_recipient = nl2br(htmlspecialchars($recipient));

    // Combine all parts into the final visual HTML structure
    $generated_content = "
        <div class='letter-page'>
            {$head}
            
            <p style='text-align: right; font-weight: bold;'>Date: " . date('F j, Y', strtotime($letter_date)) . "</p>
            
            <div style='margin-bottom: 20px; font-size: 14px;'>
                {$formatted_recipient}
            </div>
            
            <div style='margin-top: 30px; font-size: 16px; line-height: 1.6;'>
                {$formatted_body}
            </div>
            
            <p style='margin-top: 50px;'>Sincerely,</p>
            <p style='margin-top: 40px; font-weight: bold;'>[Signature Area/Name of Creator]</p>
            <p style='font-size: 12px; color: #555;'>Prepared by User ID: {$user_id}</p>
            
            {$foot}
        </div>
    ";
}
?>

<style>
    /* Styling for the Letterpad Input Form */
    .form-card textarea {
        min-height: 100px;
    }
    .letter-page {
        position: relative;
        padding: 40px; /* Padding for the "page" */
        background: white;
        border: 1px solid #ddd;
        box-shadow: 0 0 10px rgba(0,0,0,0.05);
        min-height: 800px; /* Mimics a page height */
        box-sizing: border-box;
        overflow: hidden;
    }
    /* Styles for print output (PDF simulation) */
    @media print {
        body > *:not(.print-container) {
            display: none;
        }
        .print-container {
            display: block;
            width: 100%;
            margin: 0;
            padding: 0;
        }
        .letter-page {
            box-shadow: none;
            border: none;
            min-height: auto;
            position: relative; /* Remove absolute positioning during print for footer */
        }
        .letter-page footer {
            position: relative;
            bottom: auto;
        }
    }
</style>

<div class="form-card">
    <h3>Company Letterpad Template Generator</h3>
    <p>Generate a formal letter using the fixed company letterhead and custom content.</p>
    
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=company_letterpad" method="post">
        
        <!-- Variable Input Fields -->
        
        <label for="document_title">Document Title (Appears below Letterhead)</label>
        <input type="text" name="document_title" id="document_title" required placeholder="e.g., Letter of Recommendation or To Whom It May Concern">

        <label for="letter_date">Date of Letter</label>
        <input type="date" name="letter_date" id="letter_date" value="<?php echo date('Y-m-d'); ?>" required>

        <label for="recipient_details">Recipient Details (Name, Address, Salutation)</label>
        <textarea name="recipient_details" id="recipient_details" rows="3" required 
            placeholder="e.g.,
Mr. John Smith
XYZ Corporation
123 Business Road
Dear Mr. Smith,"></textarea>

        <label for="body_content">Main Body Content *</label>
        <textarea name="body_content" id="body_content" rows="15" required 
            placeholder="Start writing the main text of your letter here."></textarea>
        
        <button type="submit" name="generate_letter" style="background-color: #3498db; color: white;">Generate & Save Document</button>
    </form>
</div>

<?php if (isset($generated_content)): ?>
<!-- Display the Generated Document Draft -->
<div class="form-card" style="margin-top: 20px;">
    <h3>Generated Document Draft & Download</h3>
    <p>Review the draft below. Click Download to generate a printable PDF.</p>
    
    <div style="text-align: center; margin-bottom: 20px;">
        <button onclick="downloadPdf('<?php echo htmlspecialchars($_POST['document_title'] ?? 'Company_Letterpad'); ?>')" 
                style="background-color: #e74c3c; color: white; padding: 10px 30px; border: none; border-radius: 5px;">
            <i class="fas fa-file-pdf"></i> Download as PDF
        </button>
    </div>
    
    <!-- This div holds the content to be printed/downloaded -->
    <div id="print_area" class="print-container">
        <?php echo $generated_content; ?>
    </div>
</div>

<script>
    // --- PDF Download Simulation using Print Functionality ---
    function downloadPdf(filename) {
        // 1. Get the content of the letter
        const printContent = document.getElementById('print_area').innerHTML;
        
        // 2. Open a new window and write the content there
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + filename + '</title>');
        
        // 3. Copy the necessary print styles for good layout
        printWindow.document.write(`
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
                .letter-page {
                    position: relative;
                    padding: 40px; 
                    background: white;
                    min-height: 100vh;
                    box-sizing: border-box;
                }
                .letter-page header {
                    border-bottom: 3px solid #3498db; 
                    padding-bottom: 10px; 
                    margin-bottom: 30px; 
                    text-align: center;
                }
                .letter-page h1 { color: #3498db; margin: 0; font-size: 24px; }
                .letter-page p { margin: 5px 0; font-size: 12px; color: #555; }
                .letter-page h2 { text-align: center; color: #2c3e50; border-bottom: 1px dashed #ccc; padding-bottom: 10px; }
                .letter-page footer {
                    margin-top: 60px; 
                    padding-top: 10px; 
                    border-top: 1px solid #ccc; 
                    font-size: 10px; 
                    text-align: center; 
                    color: #7f8c8d; 
                    /* Use relative positioning for printing */
                    position: relative; 
                    bottom: auto;
                }
            </style>
        `);
        printWindow.document.write('</head><body>');
        printWindow.document.write(printContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        
        // 4. Trigger the print dialog
        printWindow.focus();
        printWindow.print();
        
        // The user's browser will now handle the "Save as PDF" option.
        // For a more robust solution, a server-side PDF library (like FPDF or DOMPDF) would be required, which is beyond this single-file PHP environment.
    }
</script>
<?php endif; ?>
