<?php
// next-of-kin-appllication-api.php - REST API for Next of Kin management with approval workflow

// Load CORS configuration first
require_once __DIR__ . '/includes/cors.php';
configureCors();

// Load dependencies
require_once __DIR__ . '/includes/config_loader.php';
require_once __DIR__ . '/includes/config.php';
require_once  './includes/internal_notification_helper.php';

// Verify PDO connection exists and is valid
if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database connection not properly initialized'
    ]);
    exit();
}

// Set response headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Security headers
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// Generate CSRF token for session if not exists
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// ============================================
// AUTHENTICATION
// ============================================

// Check if user is logged in
if (!isset($_SESSION['member_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Authentication required',
        'code' => 'UNAUTHORIZED'
    ]);
    exit();
}

$memberId = (int)$_SESSION['member_id'];
$userRole = $_SESSION['role'] ?? 'member';

// ============================================
// HELPER FUNCTIONS
// ============================================

/**
 * Get users with specific permission
 */
function getUsersWithPermission($permission, $pdo) {
    try {
        // This is a placeholder - adjust based on your user/permissions table structure
        $sql = "
            SELECT DISTINCT u.id 
            FROM users u
            JOIN user_permissions up ON u.id = up.user_id
            JOIN permissions p ON up.permission_id = p.id
            WHERE p.name = ? AND u.status = 'active'
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$permission]);
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (PDOException $e) {
        error_log("Error fetching users with permission: " . $e->getMessage());
        return [];
    }
}

/**
 * Calculate age from date of birth
 */
function calculateAge($dob) {
    if (empty($dob)) return 0;
    
    $today = new DateTime();
    $birthDate = new DateTime($dob);
    return $today->diff($birthDate)->y;
}

/**
 * Get total approved inheritance percentage for member
 */
function getTotalApprovedInheritance($pdo, $memberId, $excludeKinId = null) {
    try {
        $params = [$memberId];
        $excludeClause = '';
        
        if ($excludeKinId) {
            $excludeClause = 'AND id != ?';
            $params[] = $excludeKinId;
        }
        
        $sql = "
            SELECT COALESCE(SUM(inheritance_percentage), 0) as total_percentage 
            FROM next_of_kin 
            WHERE member_id = ? AND status = 'approved' $excludeClause
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        return (float)$result['total_percentage'] ?? 0;
    } catch (PDOException $e) {
        error_log("Error calculating inheritance: " . $e->getMessage());
        return 0;
    }
}

/**
 * Validate Next of Kin data
 */
function validateKinData($data, $isEdit = false) {
    $errors = [];
    $validatedData = [];
    
    // Required fields validation
    $requiredFields = ['name', 'relationship', 'phone_number', 'inheritance_percentage', 'date_of_birth'];
    foreach ($requiredFields as $field) {
        if (!isset($data[$field]) || trim($data[$field]) === '') {
            $errors[] = ucfirst(str_replace('_', ' ', $field)) . " is required";
        }
    }
    
    if (!empty($errors)) {
        return ['valid' => false, 'errors' => $errors];
    }
    
    // Sanitize and validate data
    $validatedData['name'] = filter_var(trim($data['name']), FILTER_SANITIZE_STRING);
    $validatedData['relationship'] = filter_var(trim($data['relationship']), FILTER_SANITIZE_STRING);
    $validatedData['phone_number'] = filter_var(trim($data['phone_number']), FILTER_SANITIZE_STRING);
    $validatedData['inheritance_percentage'] = filter_var($data['inheritance_percentage'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    $validatedData['date_of_birth'] = $data['date_of_birth'];
    $validatedData['national_id_number'] = isset($data['national_id_number']) ? filter_var(trim($data['national_id_number']), FILTER_SANITIZE_STRING) : null;
    $validatedData['birth_certificate_number'] = isset($data['birth_certificate_number']) ? filter_var(trim($data['birth_certificate_number']), FILTER_SANITIZE_STRING) : null;
    
    // Phone number validation
    if (!preg_match('/^[0-9+]{10,15}$/', $validatedData['phone_number'])) {
        $errors[] = "Invalid phone number format";
    }
    
    // Inheritance percentage validation
    if ($validatedData['inheritance_percentage'] <= 0 || $validatedData['inheritance_percentage'] > 100) {
        $errors[] = "Inheritance percentage must be between 0.01 and 100";
    }
    
    // Date of birth validation
    if (!strtotime($validatedData['date_of_birth']) || strtotime($validatedData['date_of_birth']) > time()) {
        $errors[] = "Invalid date of birth";
    }
    
    // Calculate age and validate ID requirements
    $age = calculateAge($validatedData['date_of_birth']);
    
    if ($age >= 18) {
        if (empty($validatedData['national_id_number'])) {
            $errors[] = "National ID Number is required for next of kin over 18 years";
        }
    } else {
        if (empty($validatedData['birth_certificate_number'])) {
            $errors[] = "Birth Certificate Number is required for next of kin under 18 years";
        }
    }
    
    if (!empty($errors)) {
        return ['valid' => false, 'errors' => $errors];
    }
    
    $validatedData['age'] = $age;
    return ['valid' => true, 'data' => $validatedData];
}

/**
 * Check if kin ID belongs to member
 */
function validateKinOwnership($kinId, $memberId) {
    try {
        global $pdo;
        $stmt = $pdo->prepare("SELECT id FROM next_of_kin WHERE id = ? AND member_id = ?");
        $stmt->execute([$kinId, $memberId]);
        return $stmt->fetch() !== false;
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Send notifications to approvers and member
 */
function sendNextOfKinNotifications($memberId, $kinName, $actionType, $pdo) {
    try {
        // Send to approvers
        $approvers = getUsersWithPermission('approve_next_of_kin', $pdo);
        foreach ($approvers as $approverId) {
            $notificationId = sendNotification(
                (int)$approverId,
                "Next of Kin Approval Required",
                "A new Next of Kin $actionType by member #{$memberId} needs your attention.",
                $pdo,
                "next_of_kin_approvals.php?member_id=" . urlencode($memberId),
                $memberId,
                'member',
                'carbon:user-certification',
                'info',
                'unread'
            );
            
            if ($notificationId) {
                error_log("Sent notification ID {$notificationId} to approver {$approverId}");
            }
        }
        
        // Send to member
        $actionText = $actionType === 'edit' ? 'update' : 'submission';
        sendNotification(
            $memberId,
            "Submission Received",
            "Your next of kin information has been submitted for approval.",
            $pdo,
            "next_of_kin.php",
            null,
            'system',
            'carbon:user-avatar',
            'info',
            'unread',
            'member'
        );
        
        return true;
    } catch (Exception $e) {
        error_log("Error sending notifications: " . $e->getMessage());
        return false;
    }
}

// ============================================
// REQUEST ROUTING
// ============================================

$method = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];

try {
    switch ($method) {
        case 'GET':
            handleGetRequest();
            break;
            
        case 'POST':
            handlePostRequest();
            break;
            
        case 'PUT':
            handlePutRequest();
            break;
            
        case 'DELETE':
            handleDeleteRequest();
            break;
            
        default:
            http_response_code(405);
            echo json_encode([
                'success' => false,
                'error' => 'Method not allowed',
                'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE']
            ]);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Internal server error',
        'message' => ENVIRONMENT === 'development' ? $e->getMessage() : 'Something went wrong'
    ]);
    error_log("Next of Kin API Error: " . $e->getMessage());
}

// ============================================
// REQUEST HANDLERS
// ============================================

/**
 * Handle GET requests
 */
function handleGetRequest() {
    global $pdo, $memberId;
    
    // Check for specific kin ID
    if (isset($_GET['id'])) {
        $kinId = (int)$_GET['id'];
        
        if (!validateKinOwnership($kinId, $memberId)) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => 'Next of kin not found'
            ]);
            return;
        }
        
        try {
            $sql = "
                SELECT 
                    id,
                    name,
                    relationship,
                    phone_number,
                    inheritance_percentage,
                    DATE_FORMAT(date_of_birth, '%Y-%m-%d') as date_of_birth,
                    national_id_number,
                    birth_certificate_number,
                    status,
                    created_at,
                    updated_at
                FROM next_of_kin 
                WHERE id = ? AND member_id = ?
            ";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$kinId, $memberId]);
            $kin = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$kin) {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'error' => 'Next of kin not found'
                ]);
                return;
            }
            
            // Calculate age
            $kin['age'] = calculateAge($kin['date_of_birth']);
            $kin['id_type'] = $kin['age'] >= 18 ? 'national_id' : 'birth_certificate';
            $kin['id_number'] = $kin['age'] >= 18 ? $kin['national_id_number'] : $kin['birth_certificate_number'];
            
            echo json_encode([
                'success' => true,
                'data' => $kin
            ]);
            
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'error' => 'Failed to fetch next of kin details'
            ]);
        }
        
        return;
    }
    
    // Check for pending approvals
    $showPending = isset($_GET['pending']) && $_GET['pending'] === 'true';
    
    try {
        // Get approved next of kin
        $sql = "
            SELECT 
                id,
                name,
                relationship,
                phone_number,
                inheritance_percentage,
                DATE_FORMAT(date_of_birth, '%Y-%m-%d') as date_of_birth,
                national_id_number,
                birth_certificate_number,
                status,
                created_at
            FROM next_of_kin 
            WHERE member_id = ? AND status = 'approved'
            ORDER BY name ASC
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$memberId]);
        $approvedKins = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Calculate age and total inheritance for approved kins
        $totalInheritance = 0;
        foreach ($approvedKins as &$kin) {
            $kin['age'] = calculateAge($kin['date_of_birth']);
            $kin['id_type'] = $kin['age'] >= 18 ? 'national_id' : 'birth_certificate';
            $kin['id_number'] = $kin['age'] >= 18 ? $kin['national_id_number'] : $kin['birth_certificate_number'];
            $totalInheritance += $kin['inheritance_percentage'];
        }
        
        $response = [
            'success' => true,
            'data' => [
                'approved' => $approvedKins,
                'summary' => [
                    'total_approved' => count($approvedKins),
                    'total_inheritance' => $totalInheritance,
                    'remaining_allocation' => 100 - $totalInheritance
                ]
            ]
        ];
        
        // Include pending approvals if requested
        if ($showPending) {
            $sql = "
                SELECT 
                    id,
                    name,
                    relationship,
                    phone_number,
                    inheritance_percentage,
                    DATE_FORMAT(date_of_birth, '%Y-%m-%d') as date_of_birth,
                    national_id_number,
                    birth_certificate_number,
                    DATE_FORMAT(submitted_at, '%Y-%m-%d %H:%i') as submitted_at,
                    action_type,
                    original_kin_id,
                    notes
                FROM next_of_kin_pending
                WHERE member_id = ? AND status = 'pending'
                ORDER BY submitted_at DESC
            ";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$memberId]);
            $pendingKins = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Calculate age for pending kins
            foreach ($pendingKins as &$pending) {
                $pending['age'] = calculateAge($pending['date_of_birth']);
            }
            
            $response['data']['pending'] = $pendingKins;
            $response['data']['summary']['total_pending'] = count($pendingKins);
        }
        
        echo json_encode($response, JSON_NUMERIC_CHECK);
        
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to fetch next of kin information'
        ]);
        error_log("Database error: " . $e->getMessage());
    }
}

/**
 * Handle POST requests (Create new next of kin)
 */
function handlePostRequest() {
    global $pdo, $memberId;
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Invalid JSON input',
            'json_error' => json_last_error_msg()
        ]);
        return;
    }
    
    // Validate input data
    $validation = validateKinData($input);
    
    if (!$validation['valid']) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Validation failed',
            'errors' => $validation['errors']
        ]);
        return;
    }
    
    $validatedData = $validation['data'];
    
    // Check total inheritance percentage
    $totalInheritance = getTotalApprovedInheritance($pdo, $memberId);
    
    if ($totalInheritance + $validatedData['inheritance_percentage'] > 100) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Total inheritance percentage would exceed 100%',
            'current_total' => $totalInheritance,
            'attempted_addition' => $validatedData['inheritance_percentage'],
            'remaining_allocation' => 100 - $totalInheritance
        ]);
        return;
    }
    
    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        // Insert into pending approvals table
        $sql = "
            INSERT INTO next_of_kin_pending (
                member_id, name, relationship, phone_number, 
                inheritance_percentage, date_of_birth, 
                national_id_number, birth_certificate_number,
                status, submitted_at, action_type
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW(), 'add')
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $memberId,
            $validatedData['name'],
            $validatedData['relationship'],
            $validatedData['phone_number'],
            $validatedData['inheritance_percentage'],
            $validatedData['date_of_birth'],
            $validatedData['national_id_number'],
            $validatedData['birth_certificate_number']
        ]);
        
        $pendingId = $pdo->lastInsertId();
        
        // Send notifications
        sendNextOfKinNotifications($memberId, $validatedData['name'], 'addition', $pdo);
        
        // Commit transaction
        $pdo->commit();
        
        // Get the created pending record
        $sql = "SELECT * FROM next_of_kin_pending WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$pendingId]);
        $pendingRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'message' => 'Next of kin submitted for admin approval',
            'data' => [
                'pending_id' => $pendingId,
                'next_of_kin' => $validatedData,
                'summary' => [
                    'total_inheritance' => $totalInheritance,
                    'remaining_allocation' => 100 - $totalInheritance
                ]
            ]
        ]);
        
    } catch (PDOException $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to submit next of kin for approval',
            'details' => ENVIRONMENT === 'development' ? $e->getMessage() : null
        ]);
        error_log("Add next of kin error: " . $e->getMessage());
    }
}

/**
 * Handle PUT requests (Update existing next of kin)
 */
function handlePutRequest() {
    global $pdo, $memberId;
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Invalid JSON input',
            'json_error' => json_last_error_msg()
        ]);
        return;
    }
    
    // Check for kin ID
    if (!isset($input['id']) || !is_numeric($input['id'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Next of kin ID is required'
        ]);
        return;
    }
    
    $kinId = (int)$input['id'];
    
    // Verify ownership
    if (!validateKinOwnership($kinId, $memberId)) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error' => 'Next of kin not found'
        ]);
        return;
    }
    
    // Validate input data
    $validation = validateKinData($input);
    
    if (!$validation['valid']) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Validation failed',
            'errors' => $validation['errors']
        ]);
        return;
    }
    
    $validatedData = $validation['data'];
    
    // Check total inheritance percentage (excluding this kin)
    $totalInheritance = getTotalApprovedInheritance($pdo, $memberId, $kinId);
    
    if ($totalInheritance + $validatedData['inheritance_percentage'] > 100) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Total inheritance percentage would exceed 100%',
            'current_total_without_this' => $totalInheritance,
            'attempted_addition' => $validatedData['inheritance_percentage'],
            'remaining_allocation' => 100 - $totalInheritance
        ]);
        return;
    }
    
    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        // Get current kin details for comparison
        $sql = "SELECT name FROM next_of_kin WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$kinId]);
        $currentKin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Insert into pending approvals table for edit
        $sql = "
            INSERT INTO next_of_kin_pending (
                member_id, original_kin_id, name, relationship, phone_number, 
                inheritance_percentage, date_of_birth, 
                national_id_number, birth_certificate_number,
                status, submitted_at, action_type
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW(), 'edit')
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $memberId,
            $kinId,
            $validatedData['name'],
            $validatedData['relationship'],
            $validatedData['phone_number'],
            $validatedData['inheritance_percentage'],
            $validatedData['date_of_birth'],
            $validatedData['national_id_number'],
            $validatedData['birth_certificate_number']
        ]);
        
        $pendingId = $pdo->lastInsertId();
        
        // Send notifications
        sendNextOfKinNotifications($memberId, $validatedData['name'], 'edit', $pdo);
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Next of kin update submitted for admin approval',
            'data' => [
                'pending_id' => $pendingId,
                'original_kin_id' => $kinId,
                'updated_data' => $validatedData,
                'summary' => [
                    'total_inheritance' => $totalInheritance,
                    'remaining_allocation' => 100 - $totalInheritance
                ]
            ]
        ]);
        
    } catch (PDOException $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to submit update for approval',
            'details' => ENVIRONMENT === 'development' ? $e->getMessage() : null
        ]);
        error_log("Update next of kin error: " . $e->getMessage());
    }
}

/**
 * Handle DELETE requests
 */
function handleDeleteRequest() {
    global $pdo, $memberId;
    
    // Check if deleting specific kin
    if (isset($_GET['id'])) {
        $kinId = (int)$_GET['id'];
        
        if (!validateKinOwnership($kinId, $memberId)) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => 'Next of kin not found'
            ]);
            return;
        }
        
        try {
            // Begin transaction
            $pdo->beginTransaction();
            
            // Get kin info before deletion
            $sql = "SELECT name FROM next_of_kin WHERE id = ? AND member_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$kinId, $memberId]);
            $kin = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$kin) {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'error' => 'Next of kin not found'
                ]);
                return;
            }
            
            // Create delete request in pending table
            $sql = "
                INSERT INTO next_of_kin_pending (
                    member_id, original_kin_id, action_type,
                    status, submitted_at, notes
                ) VALUES (?, ?, 'delete', 'pending', NOW(), ?)
            ";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                $memberId,
                $kinId,
                "Delete request for {$kin['name']}"
            ]);
            
            $pendingId = $pdo->lastInsertId();
            
            // Send notifications
            sendNextOfKinNotifications($memberId, $kin['name'], 'deletion', $pdo);
            
            // Commit transaction
            $pdo->commit();
            
            echo json_encode([
                'success' => true,
                'message' => 'Delete request submitted for admin approval',
                'data' => [
                    'pending_id' => $pendingId,
                    'kin_name' => $kin['name']
                ]
            ]);
            
        } catch (PDOException $e) {
            $pdo->rollBack();
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'error' => 'Failed to submit delete request',
                'details' => ENVIRONMENT === 'development' ? $e->getMessage() : null
            ]);
            error_log("Delete next of kin error: " . $e->getMessage());
        }
        
    } else {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Next of kin ID is required for deletion'
        ]);
    }
}
?>