<?php
/**
 * Export Reports
 * Export report data to CSV format
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$type = $_GET['type'] ?? 'cases';
$format = $_GET['format'] ?? 'csv';

// Set headers for download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $type . '_report_' . date('Y-m-d') . '.csv"');

$output = fopen('php://output', 'w');

switch($type) {
    case 'cases':
        // Get cases data
        $status = $_GET['status'] ?? 'all';
        $dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
        $dateTo = $_GET['date_to'] ?? date('Y-m-d');
        
        $where = "user_id = ?";
        $params = [$userId];
        if ($status != 'all') {
            $where .= " AND status = ?";
            $params[] = $status;
        }
        $where .= " AND DATE(created_at) BETWEEN ? AND ?";
        $params[] = $dateFrom;
        $params[] = $dateTo;
        
        $stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.patient_age, c.patient_gender,
                              c.chief_complaint, c.created_at, c.status, c.follow_up_date,
                              r.name as remedy_name, c.prescription_potency
                              FROM cases c
                              LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
                              WHERE $where
                              ORDER BY c.created_at DESC");
        $stmt->execute($params);
        $data = $stmt->fetchAll();
        
        fputcsv($output, ['ID', 'Patient Name', 'Mobile', 'Age', 'Gender', 'Chief Complaint', 'Created Date', 'Status', 'Follow-up Date', 'Prescribed Remedy', 'Potency']);
        foreach($data as $row) {
            fputcsv($output, [
                $row['id'], $row['patient_name'], $row['patient_mobile'], $row['patient_age'], $row['patient_gender'],
                $row['chief_complaint'], $row['created_at'], $row['status'], $row['follow_up_date'],
                $row['remedy_name'], $row['prescription_potency']
            ]);
        }
        break;
        
    case 'remedies':
        $period = $_GET['period'] ?? 'all';
        $dateRange = getDateRange($period);
        
        $stmt = $pdo->prepare("SELECT r.name, r.abbreviation,
                              COUNT(c.id) as prescription_count,
                              COUNT(DISTINCT c.patient_mobile) as unique_patients,
                              SUM(CASE WHEN c.status = 'closed' THEN 1 ELSE 0 END) as successful_count
                              FROM remedies r
                              LEFT JOIN cases c ON r.id = c.prescribed_remedy_id AND c.user_id = ?
                              WHERE c.created_at BETWEEN ? AND ? OR c.id IS NULL
                              GROUP BY r.id
                              HAVING prescription_count > 0
                              ORDER BY prescription_count DESC");
        $stmt->execute([$userId, $dateRange['start'], $dateRange['end']]);
        $data = $stmt->fetchAll();
        
        fputcsv($output, ['Remedy', 'Abbreviation', 'Prescriptions', 'Unique Patients', 'Successful Cases', 'Success Rate (%)']);
        foreach($data as $row) {
            $successRate = $row['prescription_count'] > 0 ? round(($row['successful_count'] / $row['prescription_count']) * 100, 1) : 0;
            fputcsv($output, [
                $row['name'], $row['abbreviation'], $row['prescription_count'],
                $row['unique_patients'], $row['successful_count'], $successRate
            ]);
        }
        break;
        
    case 'monthly':
        $year = $_GET['year'] ?? date('Y');
        
        $stmt = $pdo->prepare("SELECT 
                              MONTH(created_at) as month,
                              COUNT(*) as case_count,
                              SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_count,
                              SUM(CASE WHEN prescribed_remedy_id IS NOT NULL THEN 1 ELSE 0 END) as prescription_count
                              FROM cases 
                              WHERE user_id = ? AND YEAR(created_at) = ?
                              GROUP BY MONTH(created_at)");
        $stmt->execute([$userId, $year]);
        $data = $stmt->fetchAll();
        
        $monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        $monthData = [];
        for ($i = 1; $i <= 12; $i++) {
            $found = false;
            foreach ($data as $d) {
                if ($d['month'] == $i) {
                    $monthData[$i] = $d;
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $monthData[$i] = ['month' => $i, 'case_count' => 0, 'closed_count' => 0, 'prescription_count' => 0];
            }
        }
        
        fputcsv($output, ['Month', 'Cases', 'Closed', 'Prescriptions', 'Closure Rate (%)', 'Prescription Rate (%)']);
        foreach($monthData as $month) {
            $closureRate = $month['case_count'] > 0 ? round(($month['closed_count'] / $month['case_count']) * 100, 1) : 0;
            $prescriptionRate = $month['case_count'] > 0 ? round(($month['prescription_count'] / $month['case_count']) * 100, 1) : 0;
            fputcsv($output, [
                $monthNames[$month['month'] - 1], $month['case_count'], $month['closed_count'],
                $month['prescription_count'], $closureRate, $prescriptionRate
            ]);
        }
        break;
        
    default:
        fputcsv($output, ['Error', 'Invalid export type']);
        break;
}

fclose($output);
exit;
?>