<?php
// api/calendar_action.php
require_once '../config/database.php';
require_once '../includes/functions.php';

session_start();
// Basic Auth Check - Manager Access
if (!hasRole('roster_manager')) {
    die("Access Denied");
}

$action = $_POST['action'] ?? '';

try {
    } elseif ($action === 'update_event') {
        $id = (int)$_POST['id'];
        $title = clean_input($_POST['title']);
        $event_date = clean_input($_POST['event_date']);
        $event_time = !empty($_POST['event_time']) ? $_POST['event_time'] : null;
        $prayer_time = !empty($_POST['prayer_time']) ? $_POST['prayer_time'] : null;
        $description = clean_input($_POST['description']);

        // Check Sunday Logic for single update
        $dw = date('w', strtotime($event_date));
        if ($dw == 0) {
            $prayer_time = '07:30'; 
        }

        $stmt = $pdo->prepare("UPDATE calendar_events SET title=?, event_date=?, event_time=?, prayer_time=?, description=? WHERE id=?");
        $stmt->execute([$title, $event_date, $event_time, $prayer_time, $description, $id]);

        header("Location: ../index.php?page=calendar_manager&msg=Event updated.");
        exit;

    } elseif ($action === 'manual_add') {
        $title = clean_input($_POST['title']);
        $event_date = clean_input($_POST['event_date']);
        $event_time = !empty($_POST['event_time']) ? $_POST['event_time'] : null;
        $prayer_time = !empty($_POST['prayer_time']) ? $_POST['prayer_time'] : null;
        $description = clean_input($_POST['description']);

        if (!$title || !$event_date) die("Title and Date required.");

        // Check Recurrence
        $freq = $_POST['recurrence_freq'] ?? 'none';
        $endDate = !empty($_POST['recurrence_end']) ? clean_input($_POST['recurrence_end']) : null;
        
        $datesToAdd = [];
        $datesToAdd[] = $event_date; // Always add the initial date

        if ($freq !== 'none' && $endDate && strtotime($endDate) > strtotime($event_date)) {
            $current = strtotime($event_date);
            $end = strtotime($endDate);
            $safety = 0;
            
            while ($safety < 365) { // Limit to 1 year of recurring events just in case
                // Increment based on freq
                if ($freq === 'daily') $current = strtotime('+1 day', $current);
                elseif ($freq === 'weekly') $current = strtotime('+1 week', $current);
                elseif ($freq === 'monthly') $current = strtotime('+1 month', $current);
                
                if ($current > $end) break;
                
                $datesToAdd[] = date('Y-m-d', $current);
                $safety++;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO calendar_events (title, event_date, event_time, prayer_time, description) VALUES (?, ?, ?, ?, ?)");
        
        $pdo->beginTransaction();
        foreach ($datesToAdd as $d) {
            // Apply Sunday Logic per date
            $targetPrayer = $prayer_time; // Default to user input
            $dw = date('w', strtotime($d));
            
            if ($dw == 0) { // Sunday
                $targetPrayer = '07:30'; 
            }
            
            $stmt->execute([$title, $d, $event_time, $targetPrayer, $description]);
        }
        $pdo->commit();

        $count = count($datesToAdd);
        header("Location: ../index.php?page=calendar_manager&msg=$count event(s) added.");
        exit;

    } elseif ($action === 'delete') {
        $id = (int)$_POST['id'];
        $pdo->query("DELETE FROM calendar_events WHERE id = $id");
        
        header("Location: ../index.php?page=calendar_manager&msg=Event deleted.");
        exit;

    } elseif ($action === 'csv_import') {
        if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            die("File upload failed.");
        }

        $file = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($file, "r");
        
        // Headers: Date, Title, Time, Prayer Time, Description
        // Skip header row
        fgetcsv($handle);

        $pdo->beginTransaction();
        $import_count = 0;
        
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            // Mapping: 0=Date, 1=Title, 2=Time, 3=Prayer Time, 4=Desc
            $rawDate = trim($data[0] ?? '');
            $title = trim($data[1] ?? '');

            if (empty($rawDate) || empty($title)) continue;

            // 1. Handle Ranges (e.g., "13/01/2026 – 15/01/2026" or "13/01/2026 - 15/01/2026")
            // Split by En Dash (–) or standard Dash (-) or " to "
            $dateParts = preg_split('/[\x{2013}-]| to /u', $rawDate);
            $startDateStr = trim($dateParts[0]);

            // 2. Parse Date (Expect DD/MM/YYYY or YYYY-MM-DD)
            $dateObj = null;
            
            // Try standard formats
            // Replace slashes with dashes for standard strtotime usage (European DD-MM-YYYY vs US MM/DD/YYYY)
            // But actually, str_replace('/', '-', $str) makes PHP assume European d-m-y
            $normalizedDate = str_replace('/', '-', $startDateStr);
            $timestamp = strtotime($normalizedDate);

            if ($timestamp !== false && $timestamp > 0) {
                // Check if year is valid (avoid 0000 or -0001)
                $Y = date('Y', $timestamp);
                if ($Y > 1970 && $Y < 2038) { // Basic sanity check
                     $date = date('Y-m-d', $timestamp);
                } else {
                     // Fallback for weird parsing
                     $date = null;
                }
            } else {
                 $date = null;
            }

            // Explicit check for DD/MM/YYYY if above failed or to be safer
            if (!$date) {
                $d = DateTime::createFromFormat('d/m/Y', $startDateStr);
                if ($d && $d->format('d/m/Y') === $startDateStr) {
                    $date = $d->format('Y-m-d');
                }
            }

            // If completely failed, skip
            if (!$date) continue;
            
            $time = !empty($data[2]) ? date('H:i', strtotime($data[2])) : null;
            
            // Logic for Prayer Time
            $prayer = !empty($data[3]) ? date('H:i', strtotime($data[3])) : null;
            
            // Enforce Sunday Rule
            $dw = date('w', strtotime($date));
            if ($dw == 0) {
                $prayer = '07:30';
            }
            
            $desc = trim($data[4] ?? '');

            $stmt = $pdo->prepare("INSERT INTO calendar_events (title, event_date, event_time, prayer_time, description) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$title, $date, $time, $prayer, $desc]);
            $import_count++;
        }
        
        $pdo->commit();
        fclose($handle);
        
        header("Location: ../index.php?page=calendar_manager&msg=Imported $import_count events.");
        exit;
    }

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    header("Location: ../index.php?page=calendar_manager&error=" . urlencode("Error: " . $e->getMessage()));
    exit;
}
