<?php
ob_start();
session_start();

require_once '../includes/constants.php';
require_once '../includes/functions.php';
require_once '../includes/allstripslashes.php';

// Connect to database
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Database connection failed: " . $mysqli->connect_error);
}

// Initialize variables from POST
$name  = trim($_POST['txtname'] ?? '');
$email = trim($_POST['txtemail'] ?? '');
$no    = trim($_POST['txtno'] ?? '');
$userid = 0;

// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $msg = "Not a valid Email ID";
    header("Location: index.php?Act=checkout&payid=1&mode=edit&email=" . urlencode($email) . "&ret=T&msg=" . urlencode($msg));
    exit;
}

// Check if user already has a checkout record
$stmt = $mysqli->prepare("SELECT checkout_id FROM partners_checkout WHERE checkout_user_id = ?");
$stmt->bind_param("i", $userid);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // Update existing
    $update = $mysqli->prepare("UPDATE partners_checkout SET checkout_email = ? WHERE checkout_user_id = ?");
    $update->bind_param("si", $email, $userid);
    $update->execute();
    $update->close();
} else {
    // Insert new
    $insert = $mysqli->prepare("INSERT INTO partners_checkout (checkout_email, checkout_user_id) VALUES (?, ?)");
    $insert->bind_param("si", $email, $userid);
    $insert->execute();
    $insert->close();
}

$stmt->close();
$mysqli->close();

$msg = "Update Successful";
header("Location: index.php?Act=payments&payid=1&mode=edit&msg=" . urlencode($msg));
exit;
?>
