<?php
include "apifolder/conn.php";

echo "<h2>Creating Investment Tables...</h2>";

// Create investment_plans table
$sql1 = "CREATE TABLE IF NOT EXISTS investment_plans (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    min_amount DECIMAL(10,2) NOT NULL,
    max_amount DECIMAL(10,2) NOT NULL,
    interest_rate DECIMAL(5,2) NOT NULL,
    duration_days INT NOT NULL,
    status TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if ($conn->query($sql1) === TRUE) {
    echo "Table investment_plans created successfully<br>";
} else {
    echo "Error creating investment_plans: " . $conn->error . "<br>";
}

// Create user_investments table
$sql2 = "CREATE TABLE IF NOT EXISTS user_investments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    plan_id INT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    invested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_claim TIMESTAMP NULL,
    total_claimed DECIMAL(10,2) DEFAULT 0,
    status TINYINT(1) DEFAULT 1,
    FOREIGN KEY (plan_id) REFERENCES investment_plans(id)
)";

if ($conn->query($sql2) === TRUE) {
    echo "Table user_investments created successfully<br>";
} else {
    echo "Error creating user_investments: " . $conn->error . "<br>";
}

// Create investment_claims table
$sql3 = "CREATE TABLE IF NOT EXISTS investment_claims (
    id INT AUTO_INCREMENT PRIMARY KEY,
    investment_id INT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    claimed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (investment_id) REFERENCES user_investments(id)
)";

if ($conn->query($sql3) === TRUE) {
    echo "Table investment_claims created successfully<br>";
} else {
    echo "Error creating investment_claims: " . $conn->error . "<br>";
}

// Insert sample data
$sample_plans = [
    ['name' => 'Basic Plan', 'min_amount' => 100, 'max_amount' => 1000, 'interest_rate' => 5.00, 'duration_days' => 30],
    ['name' => 'Premium Plan', 'min_amount' => 500, 'max_amount' => 5000, 'interest_rate' => 8.00, 'duration_days' => 60],
    ['name' => 'VIP Plan', 'min_amount' => 1000, 'max_amount' => 10000, 'interest_rate' => 12.00, 'duration_days' => 90]
];

foreach ($sample_plans as $plan) {
    $sql = "INSERT INTO investment_plans (name, min_amount, max_amount, interest_rate, duration_days) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sdddd", $plan['name'], $plan['min_amount'], $plan['max_amount'], $plan['interest_rate'], $plan['duration_days']);
    if ($stmt->execute()) {
        echo "Sample plan '{$plan['name']}' inserted<br>";
    } else {
        echo "Error inserting '{$plan['name']}': " . $stmt->error . "<br>";
    }
    $stmt->close();
}

echo "<h2>Setup Complete!</h2>";
echo "<a href='index.html'>Go to Home Page</a>";

$conn->close();
?>
