<?php
require_once __DIR__ . '/../lib.php';
hw_require_auth(['client']);

$authUser = hw_get_auth_user();
$db = hw_db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = hw_input_json();
    $orderID = $input['paypal_order_id'] ?? $input['orderID'] ?? '';
    $paymentID = $input['paypal_payment_id'] ?? $input['paymentID'] ?? '';
    $amount = $input['amount'] ?? '';
    $planType = $input['plan_type'] ?? 'personal';
    $paymentMethod = $input['payment_method'] ?? 'paypal';
    
    if (!$orderID || !$paymentID || !$amount) {
        hw_json(['success' => false, 'message' => 'Missing payment details'], 400);
    }
    
    // Validate plan type
    $validPlans = ['personal', 'family'];
    if (!in_array($planType, $validPlans)) {
        hw_json(['success' => false, 'message' => 'Invalid plan type'], 400);
    }
    
    try {
        $db->beginTransaction();
        
        // Create or update membership
        $stmt = $db->prepare("
            INSERT INTO user_memberships (user_id, plan_type, status, amount, paypal_order_id, paypal_payment_id, starts_at, expires_at, created_at) 
            VALUES (?, ?, 'active', ?, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 1 MONTH), NOW())
            ON DUPLICATE KEY UPDATE 
            status = 'active', 
            plan_type = VALUES(plan_type),
            amount = VALUES(amount),
            paypal_order_id = VALUES(paypal_order_id),
            paypal_payment_id = VALUES(paypal_payment_id),
            expires_at = DATE_ADD(NOW(), INTERVAL 1 MONTH)
        ");
        $stmt->execute([$authUser['id'], $planType, $amount, $orderID, $paymentID]);
        
        // Log payment
        $stmt = $db->prepare("
            INSERT INTO payment_logs (user_id, amount, payment_method, transaction_id, status, created_at) 
            VALUES (?, ?, 'paypal', ?, 'completed', NOW())
        ");
        $stmt->execute([$authUser['id'], $amount, $paymentID]);
        
        $db->commit();
        
        hw_json(['success' => true, 'message' => 'Membership activated successfully']);
        
    } catch (Exception $e) {
        $db->rollback();
        error_log('Membership activation error: ' . $e->getMessage());
        hw_json(['success' => false, 'message' => 'Failed to activate membership'], 500);
    }
}

hw_json(['success' => false, 'message' => 'Invalid request'], 400);
?>