Your IP : 216.73.216.86


Current Path : /home/emeraadmin/public_html/pages/taskprovider/
Upload File :
Current File : /home/emeraadmin/public_html/pages/taskprovider/export_schedule.php

<?php
//enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Include Composer's autoload file to load PHPSpreadsheet
require '../../vendor/autoload.php';


require_once __DIR__ . '/../../Classes/Database.php';


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Function to export schedule tasks to Excel and return file contents
function exportScheduleToExcel($scheduleId) {
    // Establish database connection (replace with your connection logic)
    $db = new Database();
    $pdo = $db->getConn();


    // SQL query to fetch tasks with subtask dates and times formatted
    $sql = "
    SELECT
        srv.name AS service_name,
        srv.region,
        t.frequency,
        GROUP_CONCAT(DISTINCT st.subtask_date ORDER BY st.subtask_date SEPARATOR ', ') AS subtask_dates
    FROM
        tasks t
    JOIN
        subtasks st ON t.id = st.task_id
    JOIN
        services srv ON t.service_id = srv.id
    WHERE
        t.schedule_id = :schedule_id
    GROUP BY
        srv.name, srv.region, t.frequency, t.id
    ORDER BY
        srv.name, srv.region, t.frequency
";


    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':schedule_id', $scheduleId, PDO::PARAM_INT);
    $stmt->execute();
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Create a new Spreadsheet object
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // Set headers or titles in the Excel sheet
    $sheet->setCellValue('A1', 'Service Name');
    $sheet->setCellValue('B1', 'Region');
    $sheet->setCellValue('C1', 'Frequency');

    // Get all distinct subtask dates
    $distinctDates = [];
    foreach ($tasks as $task) {
        $dates = explode(', ', $task['subtask_dates']);
        $distinctDates = array_merge($distinctDates, $dates);
    }
    $distinctDates = array_unique($distinctDates);
    sort($distinctDates);

    // Set dates as headers in the Excel sheet
    $col = 'D';
    foreach ($distinctDates as $date) {
        $sheet->setCellValue($col . '1', $date);
        $sheet->getColumnDimension($col)->setWidth(12); // Adjust width as needed
        $col++;
    }

    // Populate tasks data into Excel
    $row = 2;
    foreach ($tasks as $task) {
        $sheet->setCellValue('A' . $row, $task['service_name']);
        $sheet->setCellValue('B' . $row, $task['region']);
        $sheet->setCellValue('C' . $row, $task['frequency']);

        // Split subtask dates for the current task
        $dates = explode(', ', $task['subtask_dates']);
        $col = 'D';
        foreach ($distinctDates as $date) {
            // Check if the date exists for the current task or color black
            $value = in_array($date, $dates) ? 'X' : '';

            // Set value in corresponding cell
            $cellCoordinate = $col . $row;
            $sheet->setCellValue($cellCoordinate, $value);

            // Apply black color to non-X values
            if ($value !== 'X') {
                $spreadsheet->getActiveSheet()->getStyle($cellCoordinate)
                    ->getFont()->getColor()->setARGB(Color::COLOR_BLACK);
            }

            $col++;
        }

        $row++;
    }

    // Set column widths (optional)
    $sheet->getColumnDimension('A')->setWidth(25); // Adjust width as needed
    $sheet->getColumnDimension('B')->setWidth(20);
    $sheet->getColumnDimension('C')->setWidth(15);

    // Set headers for Excel file download
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="schedule_export_' . date('Y-m-d') . '.xlsx"');
    header('Cache-Control: max-age=0');

    // Save Excel file to PHP output (browser will download it)
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
}

// Check if schedule_id is provided via GET request
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['schedule_id'])) {
    $scheduleId = $_GET['schedule_id'];

    try {
        // Export schedule to Excel and initiate download
        exportScheduleToExcel($scheduleId);
        exit; // Stop further execution after file download
    } catch (Exception $e) {
        // Handle exceptions (e.g., database errors, file saving errors)
        echo 'Error: ' . $e->getMessage();
    }
} else {
    // Handle case where schedule_id parameter is missing
    echo 'Error: Schedule ID parameter missing.';
}
?>