<?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['session_year']) || 
    !isset($_POST['payment_method']) || !isset($_POST['fee'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$memberId = $_POST['member_id'];
$sessionYear = $_POST['session_year'];
$paymentMethod = $_POST['payment_method'];
$paymentReference = isset($_POST['payment_reference']) ? $_POST['payment_reference'] : '';
$notes = isset($_POST['notes']) ? $_POST['notes'] : '';
$fee = $_POST['fee'];
$adminId = $_SESSION['admin_id'];

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Calculate new expiry date (1 year from now)
    $expiryDate = date('Y-m-d', strtotime('+1 year'));
    
    // Update member with new session and expiry date
    $query = "UPDATE members SET 
              session_from_year = ?,
              session_to_year = ?,
              membership_expiry_date = ?,
              updated_at = NOW()
              WHERE id = ?";
    
    $stmt = $conn->prepare($query);
    $stmt->execute([
        $sessionYear,
        $sessionYear + 1,
        $expiryDate,
        $memberId
    ]);
    
    // Add finance record for the renewal
    $financeQuery = "INSERT INTO finance 
                    (member_id, transaction_type, amount, payment_method, receipt_number, 
                     session_year, description, status, payment_date, processed_by, notes) 
                    VALUES 
                    (?, 'membership_fee', ?, ?, ?, ?, 'Membership renewal fee', 'completed', CURDATE(), ?, ?)";
    
    $financeStmt = $conn->prepare($financeQuery);
    $financeStmt->execute([
        $memberId,
        $fee,
        $paymentMethod,
        $paymentReference,
        $sessionYear,
        $adminId,
        $notes
    ]);
    
    $financeId = $conn->lastInsertId();
    
    // Generate receipt number if not provided
    if (empty($paymentReference)) {
        $receiptNumber = 'RCPT-' . str_pad($financeId, 5, '0', STR_PAD_LEFT);
        
        $updateReceiptQuery = "UPDATE finance SET receipt_number = ? WHERE id = ?";
        $updateReceiptStmt = $conn->prepare($updateReceiptQuery);
        $updateReceiptStmt->execute([$receiptNumber, $financeId]);
    }
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Membership renewed successfully',
        'receipt_id' => $financeId
    ]);
    
} catch (PDOException $e) {
    // Rollback transaction on error
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }
    
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
