<?php
session_start();
require_once '../config/config.php';

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

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

$member_id = $_POST['member_id'] ?? null;

if (!$member_id) {
    echo json_encode(['success' => false, 'message' => 'Member ID is required']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Get current member data
    $stmt = $conn->prepare("SELECT * FROM members WHERE id = ?");
    $stmt->execute([$member_id]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$member) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => 'Member not found']);
        exit();
    }
    
    // Calculate new expiry date (1 year from current expiry or current date, whichever is later)
    $current_expiry = new DateTime($member['membership_expiry_date']);
    $today = new DateTime();
    $new_expiry = $current_expiry > $today ? $current_expiry : $today;
    $new_expiry->add(new DateInterval('P1Y'));
    
    // Update member's expiry date
    $stmt = $conn->prepare("
        UPDATE members 
        SET membership_expiry_date = ?, 
            updated_at = CURRENT_TIMESTAMP 
        WHERE id = ?
    ");
    $stmt->execute([$new_expiry->format('Y-m-d'), $member_id]);
    
    // Log the renewal
    $stmt = $conn->prepare("
        INSERT INTO membership_renewals (member_id, previous_expiry, new_expiry, renewed_by, created_at)
        VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
    ");
    $stmt->execute([
        $member_id,
        $member['membership_expiry_date'],
        $new_expiry->format('Y-m-d'),
        $_SESSION['admin_id']
    ]);
    
    // Update membership fees table
    $stmt = $conn->prepare("
        INSERT INTO membership_fees (member_id, fee_type, amount, due_date, paid_date, status, created_at)
        VALUES (?, 'renewal', 1000, ?, CURRENT_DATE, 'paid', CURRENT_TIMESTAMP)
    ");
    $stmt->execute([$member_id, $new_expiry->format('Y-m-d')]);
    
    // Send confirmation email (basic implementation)
    $email_subject = "Membership Renewal Confirmation - KSO Chandigarh";
    $email_body = "Dear " . $member['name'] . ",\n\n";
    $email_body .= "Your membership has been renewed successfully.\n";
    $email_body .= "New expiry date: " . $new_expiry->format('F j, Y') . "\n\n";
    $email_body .= "Thank you for your continued support.\n\n";
    $email_body .= "Best regards,\nKSO Chandigarh Admin";
    
    // Log email activity
    $stmt = $conn->prepare("
        INSERT INTO email_logs (recipient_email, subject, body, status, created_at)
        VALUES (?, ?, ?, 'sent', CURRENT_TIMESTAMP)
    ");
    $stmt->execute([$member['email'], $email_subject, $email_body]);
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Membership renewed successfully',
        'new_expiry' => $new_expiry->format('Y-m-d')
    ]);
    
} catch (PDOException $e) {
    $conn->rollBack();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
