<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
session_start();
header('Content-Type: application/json; charset=utf-8');

function respond($data) { echo json_encode($data); exit; }

if (!file_exists(__DIR__ . '/db_config.php')) {
    respond(['success' => false, 'message' => 'db_config.php not found']);
}
require __DIR__ . '/db_config.php';
if (!isset($conn)) {
    respond(['success' => false, 'message' => 'Database connection failed']);
}

// ✅ Accept both POST and GET (fallback)
$email  = isset($_POST['email']) ? trim($_POST['email']) : (isset($_GET['email']) ? trim($_GET['email']) : '');
$planId = isset($_POST['plan_id']) ? (int)$_POST['plan_id'] : (isset($_GET['plan_id']) ? (int)$_GET['plan_id'] : 0);

if (empty($email)) {
    respond(['success' => false, 'message' => 'Email is required']);
}
if ($planId <= 0) {
    respond(['success' => false, 'message' => 'Invalid plan ID']);
}

try {
    // ==================== Get User ====================
    $uStmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
    $uStmt->execute([$email]);
    $user = $uStmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        respond(['success' => false, 'message' => 'User not found']);
    }

    // ==================== ✅ Check: Any active lock exists? ====================
    $acStmt = $conn->prepare("
        SELECT id, plan_name, days, end_date 
        FROM vault_locks 
        WHERE email = ? AND status = 'active' 
        ORDER BY id DESC LIMIT 1
    ");
    $acStmt->execute([$email]);
    $existingLock = $acStmt->fetch(PDO::FETCH_ASSOC);

    if ($existingLock) {
        $endDate = date('d M Y, h:i A', strtotime($existingLock['end_date']));
        respond([
            'success' => false,
            'message' => 'You already have an active ' . (int)$existingLock['days'] . 
                         '-day lock. Please wait until ' . $endDate . ' before starting a new one.'
        ]);
    }

    // ==================== Get Plan ====================
    $pStmt = $conn->prepare("SELECT * FROM vault_plans WHERE id = ? AND is_active = 1");
    $pStmt->execute([$planId]);
    $plan = $pStmt->fetch(PDO::FETCH_ASSOC);
    if (!$plan) {
        respond(['success' => false, 'message' => 'Plan not found: ID ' . $planId]);
    }

    $days = (int)$plan['days'];
    $rate = (float)$plan['interest_percent'];

    if ($days != 30 && $days != 60) {
        respond(['success' => false, 'message' => 'Only 30 or 60 days allowed']);
    }

    // ==================== Dates ====================
    $startDate = date('Y-m-d H:i:s');
    $endDate   = date('Y-m-d H:i:s', strtotime("+$days days"));

    // ==================== Insert ====================
    $conn->beginTransaction();

    $sql = "INSERT INTO vault_locks 
                (email, plan_id, plan_name, days, interest_percent, amount, expected_profit, total_return, start_date, end_date, status, created_at)
            VALUES
                (?, ?, ?, ?, ?, 0, 0, 0, ?, ?, 'active', NOW())";

    $iStmt = $conn->prepare($sql);
    if (!$iStmt) {
        $err = $conn->errorInfo();
        $conn->rollBack();
        respond(['success' => false, 'message' => 'Insert prepare failed: ' . ($err[2] ?? 'unknown')]);
    }

    $ok = $iStmt->execute([$email, $planId, $plan['name'], $days, $rate, $startDate, $endDate]);
    if (!$ok) {
        $err = $iStmt->errorInfo();
        $conn->rollBack();
        respond(['success' => false, 'message' => 'Insert failed: ' . ($err[2] ?? 'unknown')]);
    }

    $lockId = $conn->lastInsertId();
    $conn->commit();

    respond([
        'success' => true,
        'message' => 'Locked for ' . $days . ' days',
        'lock_id' => $lockId,
        'start'   => $startDate,
        'end'     => $endDate,
        'days'    => $days,
        'rate'    => $rate
    ]);

} catch (Exception $e) {
    if ($conn->inTransaction()) $conn->rollBack();
    respond(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}