<?php
require_once '../../config/database.php';
require_once '../../config/auth_enhanced.php';

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

// Check authentication
if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Validate required parameters
if (!isset($_POST['member_id']) || !isset($_POST['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$memberId = $_POST['member_id'];
$status = $_POST['status'];
$rejectionReason = isset($_POST['rejection_reason']) ? $_POST['rejection_reason'] : null;
$notes = isset($_POST['notes']) ? $_POST['notes'] : null;
$assignedTo = isset($_POST['assigned_to']) ? $_POST['assigned_to'] : null;
$adminId = $_SESSION['admin_id'];

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Get current status of the member
    $stmt = $conn->prepare("SELECT status FROM members WHERE id = ?");
    $stmt->execute([$memberId]);
    $currentStatus = $stmt->fetchColumn();
    
    if (!$currentStatus) {
        echo json_encode(['success' => false, 'message' => 'Member not found']);
        exit;
    }
    
    // Update member status
    $query = "UPDATE members SET 
              status = ?,
              updated_at = NOW()";
    $params = [$status];
    
    // Add additional fields based on the status
    switch ($status) {
        case 'approved':
            $query .= ", approved_by = ?, approved_at = NOW()";
            $params[] = $adminId;
            break;
        case 'rejected':
            $query .= ", rejection_reason = ?";
            $params[] = $rejectionReason;
            break;
        case 'under_review':
            $query .= ", assigned_to = ?, assignment_date = NOW()";
            $params[] = $assignedTo;
            break;
    }
    
    // Add assignment notes if provided
    if ($notes) {
        $query .= ", assignment_notes = ?";
        $params[] = $notes;
    }
    
    $query .= " WHERE id = ?";
    $params[] = $memberId;
    
    $updateStmt = $conn->prepare($query);
    $updateStmt->execute($params);
    
    // Log the approval action
    $actionType = '';
    switch ($status) {
        case 'approved':
            $actionType = 'approved';
            break;
        case 'rejected':
            $actionType = 'rejected';
            break;
        case 'under_review':
            $actionType = 'assigned';
            break;
    }
    
    $logQuery = "INSERT INTO member_approval_history 
                (member_id, action, performed_by, from_status, to_status, assigned_to, notes, ip_address) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    
    $logParams = [
        $memberId,
        $actionType,
        $adminId,
        $currentStatus,
        $status,
        $assignedTo,
        $notes,
        $_SERVER['REMOTE_ADDR']
    ];
    
    $logStmt = $conn->prepare($logQuery);
    $logStmt->execute($logParams);
    
    // Commit the transaction
    $conn->commit();
    
    // Success message based on status
    $message = '';
    switch ($status) {
        case 'approved':
            $message = 'Member has been approved successfully';
            break;
        case 'rejected':
            $message = 'Member has been rejected';
            break;
        case 'under_review':
            $message = 'Member has been assigned for review';
            break;
        default:
            $message = 'Member status has been updated';
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message
    ]);
    
} catch (PDOException $e) {
    // Rollback the transaction on error
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }
    
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
