<?php
/**
 * process_form.php
 * Handles lead form submission from index.html.
 * On success/error, redirects back to index.html with a ?status= query param.
 */

require_once __DIR__ . '/connect.php';

// Only handle POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.html');
    exit;
}

$name        = trim($_POST['name']        ?? '');
$phone       = trim($_POST['phone']       ?? '');
$email       = trim($_POST['email']       ?? '');
$company     = trim($_POST['company']     ?? '');
$designation = trim($_POST['designation'] ?? '');

// Basic validation
if ($name === '' || $phone === '' || $email === '' || $company === '' || $designation === '') {
    header('Location: index.html?status=error&msg=' . urlencode('Please fill all required fields.'));
    exit;
}

$mysqli = get_db_connection();

if (!($mysqli instanceof mysqli)) {
    header('Location: index.html?status=error&msg=' . urlencode('Database connection failed.'));
    exit;
}

// Ensure tables exist
$mysqli->query("CREATE TABLE IF NOT EXISTS leads (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    phone VARCHAR(64) NOT NULL,
    email VARCHAR(255) NOT NULL,
    company VARCHAR(255) NOT NULL,
    designation VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

$mysqli->query("CREATE TABLE IF NOT EXISTS users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    phone VARCHAR(64) NOT NULL,
    email VARCHAR(255) NOT NULL,
    company VARCHAR(255) NOT NULL,
    designation VARCHAR(255) NOT NULL,
    password VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// Insert lead
$stmt = $mysqli->prepare("INSERT INTO leads (name, phone, email, company, designation) VALUES (?, ?, ?, ?, ?)");
if ($stmt) {
    $stmt->bind_param('sssss', $name, $phone, $email, $company, $designation);
    if ($stmt->execute()) {
        $stmt->close();
        $mysqli->close();
        // Success: redirect with status param so index.html JS shows success modal + download link
        header('Location: index.html?status=success');
        exit;
    } else {
        $stmt->close();
        $mysqli->close();
        header('Location: index.html?status=error&msg=' . urlencode('Failed to save. Please try again.'));
        exit;
    }
} else {
    $mysqli->close();
    header('Location: index.html?status=error&msg=' . urlencode('Server error preparing statement.'));
    exit;
}
