<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available.
// NOTE: Ensure 'config/db_connection.php' is properly included in admin_dashboard.php 
// and $conn is a valid mysqli connection object.
// ** Uncomment session_start() and include in a real environment **
// session_start(); 
// include 'config/db_connection.php'; 

// --- START: USER AUTHENTICATION & VARIABLE SETUP (Required from previous request) ---
// Fallback if session is not yet started or user not logged in (FOR DEMO/TESTING ONLY)
if (!isset($_SESSION['user_id'])) {
    // Simulating logged-in user data based on your request
    $_SESSION['user_id'] = 5001; 
    $_SESSION['username'] = 'Saiyeda Marzia'; 
    $_SESSION['role'] = 'SOC Engineer'; 
}

$status_message = '';
$generated_content = null;
$user_authenticated = isset($_SESSION['user_id']);

if ($user_authenticated) {
    $user_id = $_SESSION['user_id'];
    $username = $_SESSION['username'] ?? 'Employee Name'; 
    $user_role = $_SESSION['role'] ?? 'Unspecified Role'; 
} else {
    // If user is not authenticated, prevent further processing
    $status_message = "<div class='alert alert-error'>User not authenticated. Please log in to view this page.</div>";
    $username = 'Guest';
    $user_role = 'N/A';
}

// Data from form submission (used for sticky fields)
$application_date = $_POST['application_date'] ?? date('Y-m-d');
$application_body = $_POST['application_body'] ?? '';


// --- Fixed Letterhead Components (Based on the image) ---
$company_name = "Cyberlog Ltd.";
$company_address_short = "1/6, Block: New- C, Mirpur-1, Dhaka-1216";
$company_email = "info@cyberlog.com.bd";
$company_website = "www.cyberlog.com.bd";

$recipient_name = "Hridoy Mustofa";
$recipient_title = "Founder & CEO";
$recipient_details = "Cyberlog Ltd.<br>1/6, Block: New- C, Mirpur-1,<br>Dhaka-1216, Bangladesh";


// --- FUNCTION: Builds the Leave Application HTML ---
function get_leave_application_html(
    $app_id, 
    $app_date, 
    $app_body, 
    $user_name, 
    $user_role,
    $recipient_name,
    $recipient_title,
    $recipient_details
) {
    global $company_name, $company_address_short, $company_email, $company_website;
    
    // NOTE: This HTML is optimized for clean printing/PDF generation.
    $html = "
    <div class='letter-page'>
        <div class='header-top'>
            <div class='logo-text'>Cyberlog</div>
            <div class='contact-info'>
                <p>{$company_address_short} <span style='color: #E74C3C;'>&#x1F4CD;</span></p>
                <p>{$company_email} <span style='color: #E74C3C;'>&#x2709;</span></p>
                <p>{$company_website} <span style='color: #E74C3C;'>&#x1F310;</span></p>
            </div>
        </div>
        <div style='border-bottom: 2px solid #0056b3; width: 100%; margin-top: -10px;'>&nbsp;</div>
        
        <div style='margin-top: 20px; font-size: 14px;'>
            <p><span class='plain-text'>Date:</span> <span style='border-bottom: 1px dashed #333;'>".date('F j, Y', strtotime($app_date))."</span></p>
        </div>

        <div class='plain-box' style='width: 300px; padding: 10px; margin-top: 15px;'>
            <p style='margin: 0;'>To,</p>
            <p style='margin: 0;'>{$recipient_name}</p>
            <p style='margin: 0;'>{$recipient_title}</p>
            <p style='margin: 0;'>{$recipient_details}</p>
        </div>

        <p class='plain-box' style='width: 250px; margin-top: 20px;'>Subject: Request for Leave.</p>
        <p class='plain-box' style='width: 150px;'>Dear Sir,</p>
        
        <div class='app-body-content-plain' style='padding: 15px; margin-top: 15px; min-height: 250px;'>
            ".nl2br(htmlspecialchars($app_body))."
        </div>
        
        <div class='plain-box' style='width: 250px; margin-top: 40px; padding: 15px;'>
            <p style='margin: 0;'>Sincerely,</p>
            <p style='text-decoration: underline; margin: 5px 0 2px 0;'>{$user_name}</p>
            <p style='margin: 0;'>{$user_name}</p>
            <p style='margin: 0;'>{$user_role},</p>
            <p style='margin: 0;'>{$company_name}</p>
        </div>

        <div style='width: 100%; margin-top: 40px; border-bottom: 10px solid #0056b3;'>&nbsp;</div>
    </div>
    ";
    return $html;
}


// --- Logic to View a Specific Leave Application (Unchanged) ---
if ($user_authenticated && isset($_GET['view_app_id']) && is_numeric($_GET['view_app_id'])) {
    $view_id = (int)$_GET['view_app_id'];
    
    // Fetch Main Leave Data (ensure created_by matches current user for security)
    $sql_main = "SELECT * FROM leave_applications WHERE id = ? AND created_by = ?";
    if (isset($conn) && $stmt_main = $conn->prepare($sql_main)) {
        $stmt_main->bind_param("ii", $view_id, $user_id);
        $stmt_main->execute();
        $result_main = $stmt_main->get_result();
        $app_record = $result_main->fetch_assoc();
        $stmt_main->close();

        if ($app_record) {
            // Generate HTML content for the viewer
            $generated_content = get_leave_application_html(
                $app_record['id'], 
                $app_record['application_date'], 
                $app_record['application_body'], 
                $username, // Note: using session/current user details for signature block
                $user_role,
                $recipient_name,
                $recipient_title,
                $recipient_details
            );
            
            $status_message = "<div class='alert alert-info'>Viewing Application ID: **{$app_record['id']}** from ".date('M j, Y', strtotime($app_record['application_date']))."</div>";
            
            // Update sticky fields with viewed data
            $application_date = $app_record['application_date'];
            $application_body = $app_record['application_body'];
            
        } else {
             $status_message = "<div class='alert alert-error'>Leave application not found or you are unauthorized to view it.</div>";
        }
    } else if ($user_authenticated) {
        $status_message = "<div class='alert alert-error'>Database connection required to view records.</div>";
    }
}


// --- Logic to Handle Form Submission (Generate & Save) ---
if ($user_authenticated && $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_and_save'])) {
    
    // 1. Sanitize & Prepare Inputs
    // Assuming $conn is available for real_escape_string. If not, use filter_input for basic sanitation.
    $application_date = isset($conn) ? $conn->real_escape_string($_POST['application_date'] ?? date('Y-m-d')) : ($_POST['application_date'] ?? date('Y-m-d'));
    $application_body = isset($conn) ? $conn->real_escape_string($_POST['application_body'] ?? '') : ($_POST['application_body'] ?? '');
    
    if (empty($application_date) || empty($application_body)) {
        $status_message = "<div class='alert alert-error'>Both the Date and the Application Body fields are required.</div>";
    } else {
        // --- Database Logic: Save to DB ---
        if (isset($conn)) {
            $sql_main = "INSERT INTO leave_applications (application_date, application_body, created_by, username) 
                         VALUES (?, ?, ?, ?)";
            
            if ($stmt_main = $conn->prepare($sql_main)) {
                $recipient_str = "{$recipient_name}, {$recipient_title}, {$company_address_short}";
                $stmt_main->bind_param("siss", $application_date, $application_body, $user_id, $username);
                
                if ($stmt_main->execute()) {
                    $last_id = $stmt_main->insert_id;
                    $status_message = "<div class='alert alert-success'>Leave Application ID **{$last_id}** generated and saved successfully!</div>";

                    // Generate HTML Content for the Draft Viewer
                    $generated_content = get_leave_application_html(
                        $last_id, 
                        $application_date, 
                        $application_body, 
                        $username, 
                        $user_role,
                        $recipient_name,
                        $recipient_title,
                        $recipient_details
                    );
                    
                } else {
                    $status_message = "<div class='alert alert-error'>Database error: " . $stmt_main->error . "</div>";
                }
                $stmt_main->close();
            } else {
                $status_message = "<div class='alert alert-error'>Database preparation error: " . $conn->error . "</div>";
            }
        } else {
            // No database connection available (development/testing environment)
            $status_message = "<div class='alert alert-success'>Leave Application generated successfully (DB save skipped in demo mode).</div>";
            
            // Generate HTML Content for the Draft Viewer
            $generated_content = get_leave_application_html(
                'DRAFT', 
                $application_date, 
                $application_body, 
                $username, 
                $user_role,
                $recipient_name,
                $recipient_title,
                $recipient_details
            );
        }
    }
}
?>

<style>
    /* General Styling */
    .form-card { background: white; padding: 25px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); margin-bottom: 20px; }
    h3 { color: #0056b3; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-top: 0; }
    
    /* Alerts (From expense.php) */
    .alert-error { background-color: #fbecec; border: 1px solid #e74c3c; color: #e74c3c; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-success { background-color: #e8f5e9; border: 1px solid #2ecc71; color: #2ecc71; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-info { background-color: #ebf5fb; border: 1px solid #3498db; color: #3498db; padding: 10px; border-radius: 5px; margin-bottom: 10px; }

    /* --- KEY CHANGES: REMOVING BOX COLORS AND BOLDNESS --- */
    input[type="date"], textarea { 
        width: 100%; 
        padding: 10px; 
        border: 1px solid #ccc; /* Generic light border for input fields */
        box-sizing: border-box; 
        margin-top: 5px; 
        font-size: 16px; 
        margin-bottom: 15px; 
    }
    textarea { min-height: 200px; resize: vertical; }

    /* Removes green background, border, and bold from fixed text elements */
    .fixed-green-box { 
        background-color: white !important; /* Force white background */
        border: none !important; /* Remove border */
        padding: 0; /* Tighten padding */
        margin-bottom: 5px; 
        display: block; 
        font-weight: normal !important; /* Remove bold */
    }
    .label-group { margin-bottom: 15px; }

    /* Button Group (From expense.php) */
    .button-group-aligned { margin-top: 30px; display: flex; justify-content: space-between; align-items: center; width: 100%; }
    .right-aligned-buttons { display: flex; gap: 10px; }
    .action-button { min-width: 150px; text-align: center; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; text-decoration: none; font-weight: bold; transition: background-color 0.3s; display: inline-block; }
    .primary-btn { background-color: #5d9cec; color: white; }
    .warning-btn { background-color: #ffcc66; color: #333; }
    .secondary-btn { background-color: #aab8c2; color: white; }
    .secondary-btn:hover { background-color: #8c97a1; }
    .download-btn { background-color: #e74c3c; color: white; }

    /* Table Styles (From expense.php) */
    .app-history-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
    .app-history-table th, .app-history-table td { border: 1px solid #ccc; padding: 8px; text-align: left; font-size: 14px; }
    .app-history-table th { background-color: #f2f2f2; font-weight: bold; }

    /* Letterhead Preview Styles (Customized from expense.php) */
    .letter-page { padding: 30px; background: white; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0,0,0,0.05); min-height: 900px; box-sizing: border-box; }
    .header-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
    .logo-text { font-size: 30px; font-weight: bold; color: #0056b3; }
    .contact-info { text-align: right; font-size: 12px; color: #555; }
    .contact-info p { margin: 0; }
    
    /* Print Styles (Crucial for PDF download look) */
    @media print {
        body > *:not(.print-container-wrapper) { display: none; }
        .print-container-wrapper { display: block !important; width: 100%; margin: 0; padding: 0; }
        .letter-page { box-shadow: none; border: none; min-height: auto; position: relative; }
        
        /* Ensure print output is plain */
        .plain-box { background-color: white !important; border: none !important; font-weight: normal !important; }
        .app-body-content-plain { border: none !important; }

        /* Final print control */
        @page { size: A4; margin: 0.5in; }
        * { -webkit-print-color-adjust: exact !important; color-adjust: exact !important; }
    }
</style>

<div class="form-card">
    <h3>New Leave Application (Logged in as: <?php echo htmlspecialchars($username); ?>)</h3>
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=leave_application" method="post" id="leaveApplicationForm">
        
        <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user_id); ?>">

        <div class="label-group">
            <label for="application_date" class="fixed-green-box" style="width: 100px; padding: 0 0 5px 0;">Date</label>
            <input type="date" name="application_date" id="application_date" required 
                   value="<?php echo htmlspecialchars($application_date); ?>">
        </div>

        <div class="fixed-green-box" style="width: 300px;">
            
            <p style="margin: 0;"><?php echo $recipient_name; ?></p>
            <p style="margin: 0;"><?php echo $recipient_title; ?></p>
            <p style="margin: 0;"><?php echo $recipient_details; ?></p>
        </div>
		<br/>
        <p class="fixed-green-box" style="width: 350px;">Subject: Request for Leave.</p>
		<br/>
        <p class="fixed-green-box" style="width: 150px;">Dear Sir,</p>
        
        <div class="label-group">
            <textarea name="application_body" id="application_body" required 
                      placeholder="Enter the body of your leave application here (e.g., reason, start date, end date, total days)."><?php echo htmlspecialchars($application_body); ?></textarea>
        </div>

        <div class="fixed-green-box" style="width: 300px;">
            <p style="margin: 0;">Sincerely,</p>
            <p style="margin: 0;"><?php echo htmlspecialchars($username); ?></p>
            <p style="margin: 0;"><?php echo htmlspecialchars($user_role); ?></p>
			<p style="margin: 0;">Cyberlog Ltd.</p>
        </div>
        
        <div class="button-group-aligned">
            <button type="submit" name="generate_and_save" class="action-button primary-btn">
                Generate PDF & Save
            </button>
            
            <div class="right-aligned-buttons">
                <button type="reset" class="action-button warning-btn">
                    Reset Form
                </button>
                <a href="admin_dashboard.php" class="action-button secondary-btn">
                    Cancel
                </a>
            </div>
        </div>
    </form>
</div>

<?php if (isset($generated_content)): ?>
<div class="form-card print-container-wrapper" style="margin-top: 20px;">
    <h3>Generated Leave Application Draft & Download</h3>
    
    
    <div style="text-align: center; margin-bottom: 20px;">
        <button onclick="downloadPdf('<?php echo 'Leave_Application_' . date('Ymd'); ?>')" 
                class="action-button download-btn">
            <i class="fas fa-file-pdf"></i> Download as PDF
        </button>
        <a href="admin_dashboard.php?page=leave_application" 
                class="action-button primary-btn" style="margin-left: 10px;">
            + Create New
        </a>
    </div>
    
    <div id="print_area" class="print-container">
        <?php echo $generated_content; ?>
    </div>
</div>
<?php endif; ?>

<div class="form-card" style="margin-top: 40px;">
    <h3>Saved Leave Application History</h3>
    
    <?php
    $sql_history = "SELECT id, application_date, username, created_at FROM leave_applications WHERE created_by = ? ORDER BY created_at DESC LIMIT 10";
    $app_history = [];
    
    if (isset($conn) && $user_authenticated) {
        $stmt_history = $conn->prepare($sql_history);
        if ($stmt_history) {
            $stmt_history->bind_param("i", $user_id);
            $stmt_history->execute();
            $result_history = $stmt_history->get_result();
            while ($row = $result_history->fetch_assoc()) {
                $app_history[] = $row;
            }
            $stmt_history->close();
        }
    }
    
    if (empty($app_history)):
    ?>
        <div class="alert alert-info">No leave applications found for your account yet.</div>
    <?php else: ?>
        <table class="app-history-table">
            <thead>
                <tr>
                    <th style="width: 10%;">ID</th>
                    <th style="width: 20%;">Application Date</th>
                    <th style="width: 30%;">Applied By</th>
                    <th style="width: 25%;">Submitted On</th>
                    <th style="width: 15%; text-align: center;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($app_history as $app): ?>
                <tr>
                    <td><?php echo htmlspecialchars($app['id']); ?></td>
                    <td><?php echo date('M d, Y', strtotime($app['application_date'])); ?></td>
                    <td><?php echo htmlspecialchars($app['username']); ?></td>
                    <td><?php echo date('M d, Y h:i A', strtotime($app['created_at'])); ?></td>
                    <td style="text-align: center;">
                        <a href="admin_dashboard.php?page=leave_application&view_app_id=<?php echo $app['id']; ?>" 
                           class="action-button" style="background-color: #3498db; padding: 5px 10px; color: white; text-decoration: none; border-radius: 3px; font-size: 0.9em;">
                            View/Download
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<script>
    // --- PDF-like Download Function using window.print() (Adapted for plain style) ---
    function downloadPdf(filename) {
        const printContent = document.getElementById('print_area').innerHTML;
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + filename + '</title>');
        
        // Include necessary CSS styles for a clean print output
        printWindow.document.write(`
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
                
                /* Copy paste the essential print styles from the main stylesheet */
                .letter-page {
                    position: relative;
                    padding: 30px; 
                    background: white;
                    box-sizing: border-box;
                    width: 100%;
                }
                .header-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
                .logo-text { font-size: 30px; font-weight: bold; color: #0056b3; }
                .contact-info { text-align: right; font-size: 12px; color: #555; }
                .contact-info p { margin: 0; }
                
                /* Ensure print output is plain (white background, no border, no bold) */
                .plain-box { background-color: white !important; border: none !important; font-weight: normal !important; }
                .app-body-content-plain { border: none !important; }

                /* Final print control */
                @page { size: A4; margin: 0.5in; }
                * { -webkit-print-color-adjust: exact !important; color-adjust: exact !important; }
            </style>
        `);
        
        printWindow.document.write('</head><body>');
        printWindow.document.write(printContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        
        // Trigger the print dialog (which allows saving as PDF)
        printWindow.focus();
        printWindow.print();
        printWindow.close(); // Close the pop-up after print dialog is closed/canceled
    }

</script>