<?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);
    
    // Get member data
    $stmt = $conn->prepare("SELECT * FROM members WHERE id = ?");
    $stmt->execute([$member_id]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$member) {
        echo json_encode(['success' => false, 'message' => 'Member not found']);
        exit();
    }
    
    // Calculate days until expiry
    $expiry_date = new DateTime($member['membership_expiry_date']);
    $today = new DateTime();
    $days_until_expiry = $today->diff($expiry_date)->days;
    
    // Determine reminder type
    $reminder_type = 'general';
    if ($days_until_expiry <= 7) {
        $reminder_type = 'urgent';
    } else if ($days_until_expiry <= 30) {
        $reminder_type = 'warning';
    }
    
    // Create reminder email
    $subject = "Membership Renewal Reminder - KSO Chandigarh";
    $body = "Dear " . $member['name'] . ",\n\n";
    
    if ($expiry_date < $today) {
        $body .= "Your membership has expired on " . $expiry_date->format('F j, Y') . ".\n";
        $body .= "Please renew your membership immediately to continue enjoying our services.\n\n";
    } else {
        $body .= "Your membership will expire on " . $expiry_date->format('F j, Y') . ".\n";
        $body .= "Please renew your membership before the expiry date.\n\n";
    }
    
    $body .= "Membership Details:\n";
    $body .= "- Member ID: " . $member['kso_id'] . "\n";
    $body .= "- Name: " . $member['name'] . "\n";
    $body .= "- Membership Type: " . $member['membership_type'] . "\n";
    $body .= "- Current Expiry: " . $expiry_date->format('F j, Y') . "\n\n";
    
    $body .= "To renew your membership, please contact our office or visit our website.\n\n";
    $body .= "Thank you for your continued support.\n\n";
    $body .= "Best regards,\nKSO Chandigarh Admin";
    
    // Log the reminder
    $stmt = $conn->prepare("
        INSERT INTO renewal_reminders (member_id, reminder_type, sent_date, email_subject, email_body, created_at)
        VALUES (?, ?, CURRENT_DATE, ?, ?, CURRENT_TIMESTAMP)
    ");
    $stmt->execute([$member_id, $reminder_type, $subject, $body]);
    
    // 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'], $subject, $body]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Renewal reminder sent successfully'
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
