<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available from admin_dashboard.php
$table_name = 'completion_certificates_pdf';
$status_message = "";
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 for safety
$generated_content = null; // Holds the HTML of the certificate for display/print

// --- Set form values for initial/sticky state ---
// Use $_POST data for sticky form state, otherwise default to empty or today's date
$completion_date_value = htmlspecialchars($_POST['completion_date'] ?? date('Y-m-d'));
$project_name_value = htmlspecialchars($_POST['project_name'] ?? '');
$completion_duration_value = htmlspecialchars($_POST['completion_duration'] ?? '');
$scope_of_work_value = htmlspecialchars($_POST['scope_of_work'] ?? '');
$completed_by_company_value = htmlspecialchars($_POST['completed_by_company'] ?? '');
$company_address_value = htmlspecialchars($_POST['company_address'] ?? '');
$task_requirements = $_POST['requirement'] ?? [];
$task_completed = $_POST['task_completed'] ?? [];


// --- 1. CERTIFICATE HTML GENERATION FUNCTION ---
function get_completion_certificate_html($data, $saved_id = null) {
    // MODIFIED: Date is now dynamic from user input
    $date = date('jS F, Y', strtotime($data['completion_date'])); // Format the user-selected date
    $certificate_title = "Certificate of Completion for Cyberlog";

    // Build the dynamic tasks table
    $tasks_table_html = "
        <table style='width: 100%; border-collapse: collapse; margin: 20px 0;'>
            <thead>
                <tr style='background-color: #f2f2f2; border: 2px solid #333;'>
                    <th style='border: 1px solid #333; padding: 10px; width: 40%; text-align: left; background-color: #e8e8e8;'>Requirements</th>
                    <th style='border: 1px solid #333; padding: 10px; width: 60%; text-align: left; background-color: #e8e8e8;'>Task Completed by Cyberlog</th>
                </tr>
            </thead>
            <tbody>
    ";

    $default_tasks = [
        
    ];
    
    // Merge fixed tasks and dynamic user input
    $all_tasks = $default_tasks;

    // Add dynamic tasks (if provided)
    if (!empty($data['requirements'])) {
        foreach ($data['requirements'] as $i => $req) {
            $task = $data['tasks_completed'][$i] ?? '';
            if (!empty(trim($req)) || !empty(trim($task))) {
                 $all_tasks[htmlspecialchars($req)] = htmlspecialchars($task);
            }
        }
    }

    foreach ($all_tasks as $req => $task) {
        $tasks_table_html .= "
            <tr>
                <td style='border: 1px solid #ccc; padding: 8px; font-size: 12px;'>{$req}</td>
                <td style='border: 1px solid #ccc; padding: 8px; font-size: 12px;'>{$task}</td>
            </tr>
        ";
    }

    $tasks_table_html .= "
            </tbody>
        </table>
    ";

    // Final HTML structure based on the image (Borders changed to standard colors)
    $html_content = "
        <div class='certificate-page'>
            <div style='text-align: right; margin-bottom: 20px; color: #333; font-weight: bold;'>
                Date: {$date}
            </div>

            <div style='border: 4px solid #333; padding: 10px; margin-bottom: 10px; text-align: center; display: inline-block; width: 50%; margin-left: 25%;'>
                <h2 style='margin: 0; font-size: 1.8em;'>Certificate of Completion</h2>
                <p style='margin: 5px 0 10px 0;'>This is to proudly certify that</p>
                <h1 style='margin: 0; font-size: 2.5em;'>Cyberlog</h1>
            </div>

            <p style='text-align: center; font-size: 1.1em;'>
                has successfully completed
            </p>
            
            <div style='border: 2px solid #333; padding: 8px; margin: 10px auto; text-align: center; font-size: 1.2em; font-weight: bold;'>
                " . htmlspecialchars($data['project_name']) . "
            </div>
            
            <div style='border: 1px solid #333; padding: 5px; margin: 10px auto; text-align: center; font-size: 1.1em;'>
                Duration: " . htmlspecialchars($data['completion_duration']) . "
            </div>
            
            <div style='text-align: center; font-weight: bold; margin-top: 30px; margin-bottom: 10px; color: #333; border: 2px solid #333; padding: 8px;'>
                Summary of Tasks and Deliverables
            </div>

            {$tasks_table_html}

            <div style='border: 2px solid #333; padding: 10px; margin-top: 30px; font-size: 1em; line-height: 1.5;'>
                " . nl2br(htmlspecialchars($data['scope_of_work'])) . "
            </div>
            
            <div style='margin-top: 50px; display: flex; justify-content: left;'>
                <div style='width: 45%; text-align: center;'>
                    <div style='border: 2px solid #333; padding: 10px;'>
                        <p style='margin: 0; font-weight: bold;'>Signature</p>
						<br/>
						<p style='margin: 5px 0 0 0;'>Name: </p>
                        <p style='margin: 5px 0 0 0;'>Designation: </p>
                        <p style='margin: 0; font-weight: bold;'>".htmlspecialchars($data['completed_by_company'])."</p>
                        <p style='margin: 0; font-size: 0.9em;'>".htmlspecialchars($data['company_address'])."</p>
                    </div>
                </div>
            </div>

        </div>
    ";

    return $html_content;
}


// --- 2. LOGIC TO LOAD A SPECIFIC CERTIFICATE for viewing ---
if (isset($_GET['view_certificate_id']) && is_numeric($_GET['view_certificate_id'])) {
    $view_id = (int)$_GET['view_certificate_id'];
    
    // Fetch Main Certificate Data (only existing columns)
    $sql_main = "SELECT certificate_id, certificate_pdf, created_by, created_at FROM {$table_name} WHERE certificate_id = ?";
    if ($stmt_main = $conn->prepare($sql_main)) {
        $stmt_main->bind_param("i", $view_id);
        $stmt_main->execute();
        $result_main = $stmt_main->get_result();
        $cert_record = $result_main->fetch_assoc();
        $stmt_main->close();

        if ($cert_record) {
            // NOTE: Since the DB only stores the PDF content, we can't reliably load saved form fields.
            // For viewing, we must regenerate the HTML from the stored BLOB content itself.
            $generated_content = $cert_record['certificate_pdf'];
            
            // We cannot fill form variables from the DB, as the necessary columns don't exist.
            // The form will remain cleared/defaulted.

            // We will simulate a basic set of data for the display logic below.
            $status_message = "<div class='alert alert-info'>Viewing Certificate ID: **{$view_id}** from ".date('M j, Y', strtotime($cert_record['created_at']))."</div>";
        } else {
             $status_message = "<div class='alert alert-error'>Certificate record not found.</div>";
        }
    }
}


// --- 3. LOGIC TO HANDLE FORM SUBMISSION (Generate & Save) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["generate_and_save"])) {
    
    // Collect user inputs
    $form_data = [
        'completion_date' => $_POST['completion_date'],
        'project_name' => $_POST['project_name'],
        'completion_duration' => $_POST['completion_duration'],
        'scope_of_work' => $_POST['scope_of_work'],
        'completed_by_company' => $_POST['completed_by_company'],
        'company_address' => $_POST['company_address'],
        'requirements' => $_POST['requirement'] ?? [],
        'tasks_completed' => $_POST['task_completed'] ?? []
    ];

    // Generate HTML Content for the Draft Viewer
    $generated_content_html = get_completion_certificate_html($form_data);

    // --- Database Logic: Save HTML to DB ---
    if (!isset($conn)) {
        $status_message = "<div class='alert alert-error'>Error: Database connection object (\$conn) is not available.</div>";
    } else {
        // FIXED: Using only the existing columns: certificate_pdf, created_by, created_at
        $sql = "INSERT INTO {$table_name} (
            certificate_pdf, 
			created_by,
            created_at
        ) VALUES (?, ?, NOW())";
        
        $stmt = $conn->prepare($sql);
        // Bind: 's' for certificate_pdf (TEXT/BLOB), 'i' for user_id
        $stmt->bind_param("si", 
            $generated_content_html,
            $user_id
        );
        
        if ($stmt->execute()) {
            $last_id = $conn->insert_id;
            $status_message = "<div class='alert alert-success'>Certificate generated and saved successfully with ID: " . $last_id . ". The draft is displayed below.</div>";
            $generated_content = $generated_content_html; // Load the HTML into the display variable
            
            // Clear sticky variables on SUCCESS for a fresh form
            $completion_date_value = date('Y-m-d');
            $project_name_value = '';
            $completion_duration_value = '';
            $scope_of_work_value = '';
            $completed_by_company_value = '';
            $company_address_value = '';
            $task_requirements = [];
            $task_completed = [];

        } else {
            $status_message = "<div class='alert alert-error'>Error saving to database: " . $stmt->error . "</div>";
        }
        $stmt->close();
    }
}
?>

<style>
    /* General styles for alerts and buttons, matching convey_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; }
    .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: #3498db; color: white; }
    .primary-btn:hover { background-color: #2980b9; }
    .warning-btn { background-color: #ffcc66; color: #333; }
    .warning-btn:hover { background-color: #f6b300; }
    .secondary-btn { background-color: #aab8c2; color: white; }
    .secondary-btn:hover { background-color: #8c97a1; }
    
    /* Styles for the certificate draft area */
    .certificate-page { 
        padding: 40px; 
        background: white; 
        border: 1px solid #ddd; 
        box-shadow: 0 0 10px rgba(0,0,0,0.05); 
        box-sizing: border-box; 
        margin: 20px auto; 
        max-width: 800px;
    }
    
    @media print {
        body > *:not(.print-container) { display: none; }
        .print-container { display: block; width: 100%; margin: 0; padding: 0; }
        .certificate-page { box-shadow: none; border: none; min-height: auto; width: 100%; }
        /* Ensure the task table is fully visible in print */
        .certificate-page table { border-collapse: collapse; }
        .certificate-page table th, .certificate-page table td { border: 1px solid #333 !important; }
    }
</style>
<div class="form-card">
    <h3>Completion Certificate Generator</h3>
    
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=completion_certificate" method="post">
        
        <div style="border: 2px solid #333; padding: 15px; margin-bottom: 20px; background-color: #ffffff;">
            <div class="form-group">
                <label for="completion_date" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Certificate Date:</label>
                <input type="date" id="completion_date" name="completion_date" value="<?php echo $completion_date_value; ?>" required
                       style="border: 1px solid #ccc; width: 100%; padding: 8px;">
            </div>
            <h4 style="text-align: center; color: #333; font-size: 1.5em;">Certificate of Completion for Cyberlog</h4>
            <p style="text-align: center; font-weight: bold; color: #333;">Summary of Tasks Table Included</p>
        </div>

        <div class="form-group">
            <label for="project_name" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Project Name:</label>
            <input type="text" id="project_name" name="project_name" value="<?php echo $project_name_value; ?>" required 
                   style="border: 1px solid #ccc; width: 100%; padding: 8px;">
            </div>

        <div class="form-group">
            <label for="completion_duration" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Duration:</label>
            <input type="text" id="completion_duration" name="completion_duration" value="<?php echo $completion_duration_value; ?>" required 
                   style="border: 1px solid #ccc; width: 100%; padding: 8px;">
        </div>

        <div class="table-section" style="border: 1px solid #333; padding: 15px; margin: 20px 0; background-color: #ffffff;">
            <h4 style="color: #333; border-bottom: 1px solid #333; padding-bottom: 5px;">Custom Tasks to Add to Table (Appears after Fixed Tasks)</h4>
            
            <div id="tasks-container">
                <?php 
                // Logic: show sticky tasks if submitted/viewing, else show 1 empty row
                $num_rows = count($task_requirements) > 0 ? count($task_requirements) : 1;
                for ($i = 0; $i < $num_rows; $i++): 
                    $req = htmlspecialchars($task_requirements[$i] ?? '');
                    $task = htmlspecialchars($task_completed[$i] ?? '');
                ?>
                <div class="task-row" style="display: flex; margin-bottom: 10px;">
                    <input type="text" name="requirement[]" placeholder="Custom Requirement" value="<?php echo $req; ?>" style="flex: 1; margin-right: 10px; border: 1px solid #ccc;">
                    <input type="text" name="task_completed[]" placeholder="Custom Task Completed" value="<?php echo $task; ?>" style="flex: 1; margin-right: 10px; border: 1px solid #ccc;">
                    <button type="button" class="remove-task-btn" style="background-color: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">Remove</button>
                </div>
                <?php endfor; ?>
            </div>
            <button type="button" id="add-task-btn" style="background-color: #28a745; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; margin-top: 10px;">Add Another Task</button>
        </div>

        <div class="form-group">
            <label for="scope_of_work" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Concluding Statement:</label>
            <textarea id="scope_of_work" name="scope_of_work" required 
                      style="border: 1px solid #ccc; width: 100%; min-height: 100px; padding: 8px; resize: vertical;"><?php echo $scope_of_work_value; ?></textarea>
        </div>

        <div class="form-group">
            <label for="completed_by_company" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Signatory Company:</label>
            <input type="text" id="completed_by_company" name="completed_by_company" value="<?php echo $completed_by_company_value; ?>" required style="border: 1px solid #ccc; width: 100%; padding: 8px;">
        </div>

        <div class="form-group">
            <label for="company_address" style="color: #333; font-weight: bold; border-left: 3px solid #333; padding-left: 5px;">Signatory Address:</label>
            <input type="text" id="company_address" name="company_address" value="<?php echo $company_address_value; ?>" required style="border: 1px solid #ccc; width: 100%; padding: 8px;">
        </div>

        <div class="button-group-aligned">
            <button type="submit" name="generate_and_save" class="action-button primary-btn">
                Generate & Save Certificate
            </button>
            <div class="right-aligned-buttons">
                <button type="reset" class="action-button warning-btn">
                    Reset Form
                </button>
                <a href="admin_dashboard.php?page=manage_templates" 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 Certificate Draft & Download</h3>
    <p>Review the draft below. Click Download to open a printable PDF view.</p>
    
    <div style="text-align: center; margin-bottom: 20px;">
        <button onclick="downloadPdf('Completion_Certificate_Draft_<?php echo date('Ymd'); ?>')" 
                style="background-color: #e74c3c; color: white; padding: 10px 30px; border: none; border-radius: 5px;">
            Download as PDF
        </button>
        <button onclick="window.location.href='admin_dashboard.php?page=completion_certificate';" 
                style="background-color: #5d9cec; color: white; padding: 10px 30px; border: none; border-radius: 5px; margin-left: 10px;">
            + Create New
        </button>
    </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 Certificate History</h3>
    
    <?php
    // FIXED: Only selecting columns known to exist in the database (certificate_id, created_at)
    $sql_history = "SELECT certificate_id, created_at FROM {$table_name} ORDER BY created_at DESC LIMIT 20";
    $cert_history = [];
    
    if ($stmt_history = $conn->prepare($sql_history)) {
        $stmt_history->execute();
        $result_history = $stmt_history->get_result();
        while ($row = $result_history->fetch_assoc()) {
            $cert_history[] = $row;
        }
        $stmt_history->close();
    }
    
    if (empty($cert_history)):
    ?>
        <div class="alert alert-info">No certificates found yet. Create one above!</div>
    <?php else: ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 25%;">ID</th>
                    <th style="width: 50%;">Date Created</th>
                    <th style="width: 25%; text-align: center;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($cert_history as $cert): ?>
                <tr>
                    <td><?php echo htmlspecialchars($cert['certificate_id']); ?></td>
                    <td><?php echo date('M d, Y, h:i A', strtotime($cert['created_at'])); ?></td>
                    <td style="text-align: center;">
                        <a href="admin_dashboard.php?page=completion_certificate&view_certificate_id=<?php echo $cert['certificate_id']; ?>" 
                           class="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>
    // JavaScript for adding/removing dynamic task rows
    document.addEventListener('DOMContentLoaded', function() {
        const tasksContainer = document.getElementById('tasks-container');
        const addTaskBtn = document.getElementById('add-task-btn');

        const createNewRow = (req = '', task = '') => {
            const newRow = document.createElement('div');
            newRow.classList.add('task-row');
            newRow.style.cssText = 'display: flex; margin-bottom: 10px;';
            newRow.innerHTML = `
                <input type="text" name="requirement[]" placeholder="Custom Requirement" value="${req}" style="flex: 1; margin-right: 10px; border: 1px solid #ccc;">
                <input type="text" name="task_completed[]" placeholder="Custom Task Completed" value="${task}" style="flex: 1; margin-right: 10px; border: 1px solid #ccc;">
                <button type="button" class="remove-task-btn" style="background-color: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">Remove</button>
            `;
            tasksContainer.appendChild(newRow);
        };

        addTaskBtn.addEventListener('click', () => createNewRow());

        tasksContainer.addEventListener('click', function(event) {
            if (event.target.classList.contains('remove-task-btn')) {
                event.target.closest('.task-row').remove();
            }
        });
        
        // Ensure at least one task row exists initially if the container is empty
        if (tasksContainer.children.length === 0) {
            // Check if there's sticky data from PHP (for viewing or failed post)
            const initialReqs = <?php echo json_encode($task_requirements); ?>;
            const initialTasks = <?php echo json_encode($task_completed); ?>;

            if (initialReqs.length > 0) {
                // Populate from sticky data
                for (let i = 0; i < initialReqs.length; i++) {
                    createNewRow(initialReqs[i], initialTasks[i]);
                }
            } else {
                // Initial empty load, create one row
                createNewRow();
            }
        }
    });

    // JavaScript function to simulate PDF download using the print feature
    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 the necessary CSS styles for the print view
        printWindow.document.write(`
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: white; }
                .certificate-page {
                    position: relative;
                    padding: 40px; 
                    background: white;
                    min-height: 100vh;
                    box-sizing: border-box;
                    width: 100%;
                }
                .certificate-page h1, .certificate-page h2 { color: #333; }
                .certificate-page table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                /* Ensure all borders are visible in print */
                .certificate-page table th, .certificate-page table td { 
                    border: 1px solid #333 !important; 
                    padding: 8px; 
                    font-size: 12px;
                }
                .certificate-page table thead tr { background-color: #f2f2f2; }
                /* Ensure the boxes (Red/Green) are styled appropriately for print */
                .certificate-page > div { border-color: #333 !important; }
            </style>
        `);
        printWindow.document.write('</head><body>');
        printWindow.document.write('<div class="print-container">'); // Wrap content for print media query
        printWindow.document.write(printContent);
        printWindow.document.write('</div>');
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        
        printWindow.focus();
        printWindow.print();
    }
</script>