<?php
// employee_leaves.php

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

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

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

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

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

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // --- MODIFIED GET REQUEST to include approved_days ---
        $sql_select_base = "
            SELECT el.*, 
                   ed.surname, 
                   ed.given_name, 
                   ed.othername,
                   ed.department,
                   ed.branch_region as region
            FROM employee_leaves el
            INNER JOIN employee_details ed ON el.emp_no = ed.emp_no";
    
        if (isset($_GET['id'])) {
            // Fetch single leave with employee details
            $sql = $sql_select_base . " WHERE el.id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':id' => $_GET['id']]);
            echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
        } else {
            // Fetch all leaves with employee details
            $stmt = $pdo->query($sql_select_base);
            echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
        }
        break;
        // --- END MODIFICATION FOR GET REQUEST ---
    

    case 'POST':
        try {
            $data = json_decode(file_get_contents('php://input'), true);
            if (!$data) {
                throw new Exception("Invalid input.");
            }

            // Calculate total days
            $start_date = new DateTime($data['start_date']);
            $end_date = new DateTime($data['end_date']);
            $interval = $start_date->diff($end_date);
            // Add 1 to include the start day in the count
            $total_days = $interval->days + 1;
            
            $data['total_days'] = $total_days;
            $data['status'] = 'Pending';
            $data['created_at'] = date('Y-m-d H:i:s');
            
            $id = $crud->create($data);
            echo json_encode(['id' => $id]);
        } 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;
        $status = strtolower($data['status'] ?? '');

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

        // Handle approval or rejection with respective fields
        if (in_array($status, ['approved', 'rejected'])) {
            $now = date('Y-m-d H:i:s');
            $updateData = [
                'status' => ucfirst($status),
                'updated_at' => $now,
            ];

            if ($status === 'approved') {
                $updateData['approved_by'] = $data['approved_by'] ?? 'Admin';
                $updateData['approval_date'] = $now;
                
                // Add new reason and approved_days fields
                if (isset($data['approval_reason'])) {
                    $updateData['approval_reason'] = $data['approval_reason'];
                }
                if (isset($data['approved_days'])) {
                    $updateData['approved_days'] = $data['approved_days'];
                }
            } elseif ($status === 'rejected') {
                $updateData['rejected_by'] = $data['rejected_by'] ?? 'Admin';
                $updateData['rejection_date'] = $now;
                 // Add new reason field
                if (isset($data['rejection_reason'])) {
                    $updateData['rejection_reason'] = $data['rejection_reason'];
                }
            }

            $crud->update($id, $updateData);
            echo json_encode(['status' => 'updated', 'action' => ucfirst($status)]);
        } else {
            // Generic update
            unset($data['id']);
            $data['updated_at'] = date('Y-m-d H:i:s');
            $crud->update($id, $data);
            echo json_encode(['status' => 'updated']);
        }
        break;

    case 'DELETE':
        parse_str(file_get_contents("php://input"), $_DELETE);
        $id = $_DELETE['id'] ?? null;
        if ($id) {
            $crud->delete($id);
            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']);
}
