<?php
/**
 * Enterprise HRM ERP System - Leave Application Action API
 * Handles approve/reject actions for leave applications
 */

require_once __DIR__ . '/../includes/init.php';
requireLogin();

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Check if user has permission (Super Admin or HR Admin)
if (!isSuperAdmin() && !isHRAdmin()) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to approve/reject leave applications.']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

$leaveId = isset($input['leave_id']) ? (int)$input['leave_id'] : 0;
$action = isset($input['action']) ? trim($input['action']) : '';
$reason = isset($input['reason']) ? trim($input['reason']) : '';

// Validate inputs
if ($leaveId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid leave application ID.']);
    exit;
}

if (!in_array($action, ['approve', 'reject'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid action. Use "approve" or "reject".']);
    exit;
}

if ($action === 'reject' && empty($reason)) {
    echo json_encode(['success' => false, 'message' => 'Rejection reason is required.']);
    exit;
}

$siteId = getCurrentSiteId();
$userId = getCurrentUserId();

try {
    $db = getDB();
    
    // Get leave application details
    $stmt = $db->prepare("
        SELECT la.*, e.employee_code, e.site_id as emp_site_id,
               CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
               lt.leave_type_name
        FROM leave_applications la
        INNER JOIN employees e ON la.employee_id = e.employee_id
        LEFT JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
        WHERE la.leave_application_id = ?
    ");
    $stmt->execute([$leaveId]);
    $leave = $stmt->fetch();
    
    if (!$leave) {
        echo json_encode(['success' => false, 'message' => 'Leave application not found.']);
        exit;
    }
    
    // Verify the leave is from the current site (for HR Admin)
    if (!isSuperAdmin() && $leave['site_id'] != $siteId) {
        echo json_encode(['success' => false, 'message' => 'You can only manage leave applications from your branch.']);
        exit;
    }
    
    // Check if already processed
    if ($leave['application_status'] !== 'pending') {
        echo json_encode(['success' => false, 'message' => 'This leave application has already been ' . $leave['application_status'] . '.']);
        exit;
    }
    
    // Process the action
    $newStatus = ($action === 'approve') ? 'approved' : 'rejected';
    
    if ($action === 'approve') {
        $stmt = $db->prepare("
            UPDATE leave_applications 
            SET application_status = ?,
                approved_by = ?,
                approved_at = NOW(),
                updated_at = NOW()
            WHERE leave_application_id = ?
        ");
        $stmt->execute([$newStatus, $userId, $leaveId]);
    } else {
        $stmt = $db->prepare("
            UPDATE leave_applications 
            SET application_status = ?,
                approved_by = ?,
                approved_at = NOW(),
                rejection_reason = ?,
                updated_at = NOW()
            WHERE leave_application_id = ?
        ");
        $stmt->execute([$newStatus, $userId, $reason, $leaveId]);
    }
    
    // Create notification for the employee (if they have a user account)
    try {
        $stmt = $db->prepare("SELECT user_id FROM users WHERE email = (SELECT email FROM employees WHERE employee_id = ?)");
        $stmt->execute([$leave['employee_id']]);
        $employeeUser = $stmt->fetch();
        
        if ($employeeUser) {
            $notifyTitle = ($action === 'approve') ? 'Leave Application Approved' : 'Leave Application Rejected';
            $notifyMessage = sprintf(
                "Your %s leave application from %s to %s has been %s.",
                $leave['leave_type_name'] ?? 'leave',
                date('d-M-Y', strtotime($leave['start_date'])),
                date('d-M-Y', strtotime($leave['end_date'])),
                $newStatus
            );
            
            if ($action === 'reject' && !empty($reason)) {
                $notifyMessage .= " Reason: " . $reason;
            }
            
            createNotification(
                $employeeUser['user_id'],
                $notifyTitle,
                $notifyMessage,
                $action === 'approve' ? 'success' : 'warning',
                'leave',
                $leaveId
            );
        }
    } catch (Exception $e) {
        error_log("Error creating employee notification: " . $e->getMessage());
    }
    
    $successMessage = ($action === 'approve') 
        ? "Leave application for {$leave['employee_name']} has been approved successfully."
        : "Leave application for {$leave['employee_name']} has been rejected.";
    
    echo json_encode([
        'success' => true,
        'message' => $successMessage,
        'status' => $newStatus
    ]);
    
} catch (Exception $e) {
    error_log("Error processing leave action: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred while processing the request.']);
}

