<?php
/// Turn off all error reporting to prevent HTML output
error_reporting(0);
ini_set('display_errors', 0);

// calendar_events.php
// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';

// Ensure no output before headers
if (ob_get_length()) ob_clean();

header('Content-Type: application/json');


// Set timezone to match your local server (e.g., Nairobi)
date_default_timezone_set('Africa/Nairobi');

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/PdoCrud.php';

// Instantiate the PdoCrud class for the calendar_events table
$crud = new PdoCrud($pdo, 'calendar_events', 'id');

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // Modified GET request to include employee details if event is associated with an employee
        $sql_select_base = "
            SELECT ce.*, 
                   ed.surname, 
                   ed.given_name, 
                   ed.department,
                   ed.region
            FROM calendar_events ce
            LEFT JOIN employee_details ed ON ce.employee_id = ed.id";
    
        if (isset($_GET['id'])) {
            // Fetch single event with employee details if available
            $sql = $sql_select_base . " WHERE ce.id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id' => $_GET['id']]);
            echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
        } elseif (isset($_GET['start']) && isset($_GET['end'])) {
            // Fetch events within a date range (for calendar views)
            $sql = $sql_select_base . " WHERE ce.event_date BETWEEN :start AND :end";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':start' => $_GET['start'],
                ':end' => $_GET['end']
            ]);
            echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        } else {
            // Fetch all events with employee details if available
            $stmt = $pdo->query($sql_select_base);
            echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        }
        break;

        case 'POST':
            try {
                $data = json_decode(file_get_contents('php://input'), true);
                if (!$data) {
                    throw new Exception("Invalid input.");
                }
        
                // Validate required fields
                if (empty($data['title']) || empty($data['event_date']) || empty($data['event_type'])) {
                    throw new Exception("Title, date, and type are required.");
                }
        
                // Prepare data for insertion
                $eventData = [
                    'title' => $data['title'],
                    'event_date' => date('Y-m-d', strtotime($data['event_date'])),
                    'event_type' => $data['event_type'],
                    'description' => $data['description'] ?? null,
                    'employee_id' => $data['employee_id'] ?? null,
                    'is_all_day' => isset($data['is_all_day']) ? (int)$data['is_all_day'] : 1,
                    'created_by' => $data['created_by'] ?? 'System',
                    'created_at' => date('Y-m-d H:i:s'),
                    'status' => 'Active'
                ];
        
                // Handle end date for multi-day events
                if (!empty($data['end_date'])) {
                    $eventData['end_date'] = date('Y-m-d', strtotime($data['end_date']));
                }
        
                $id = $crud->create($eventData);
                
                // Fixed SQL query - added space before WHERE
                $sql = "SELECT ce.*, 
                               ed.surname, 
                               ed.given_name, 
                               ed.department,
                               ed.region
                        FROM calendar_events ce
                        LEFT JOIN employee_details ed ON ce.employee_id = ed.id 
                        WHERE ce.id = :id";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute([':id' => $id]);
                $newEvent = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$newEvent) {
                    throw new Exception("Failed to retrieve created event");
                }
                
                echo json_encode($newEvent);
            } catch (Exception $e) {
                http_response_code(400);
                echo json_encode(['error' => $e->getMessage()]);
            }
            break;

    case 'PUT':
        $data = json_decode(file_get_contents("php://input"), true);
        $id = $data['id'] ?? null;

        if (!$id) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing id']);
            break;
        }

        try {
            // Prepare update data
            $updateData = [
                'title' => $data['title'] ?? null,
                'event_date' => isset($data['event_date']) ? date('Y-m-d', strtotime($data['event_date'])) : null,
                'event_type' => $data['event_type'] ?? null,
                'description' => $data['description'] ?? null,
                'employee_id' => $data['employee_id'] ?? null,
                'is_all_day' => isset($data['is_all_day']) ? (int)$data['is_all_day'] : null,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            // Handle end date
            if (isset($data['end_date'])) {
                $updateData['end_date'] = date('Y-m-d', strtotime($data['end_date']));
            }

            // Remove null values to avoid overwriting with NULL
            $updateData = array_filter($updateData, function($value) {
                return $value !== null;
            });

            $crud->update($id, $updateData);
            
            // Fetch the updated event with employee details if applicable
            $sql = $sql_select_base . " WHERE ce.id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id' => $id]);
            $updatedEvent = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode($updatedEvent);
        } catch (Exception $e) {
            http_response_code(400);
            echo json_encode(['error' => $e->getMessage()]);
        }
        break;

    case 'DELETE':
        parse_str(file_get_contents("php://input"), $_DELETE);
        $id = $_DELETE['id'] ?? null;
        if ($id) {
            // Soft delete by setting status to 'Deleted'
            $crud->update($id, [
                'status' => 'Deleted',
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            echo json_encode(['status' => 'deleted']);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Missing id']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}