<?php
// Enable error reporting (for debugging; remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database configuration
$dsn = "mysql:host=localhost;dbname=customer-management;charset=utf8";
$username = "root";
$password = "";

try {
    // Create PDO connection
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} 
catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Check if form was submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Collect and sanitize form inputs
    $firstname   = trim($_POST['firstname'] ?? '');
    $lastname    = trim($_POST['lastname'] ?? '');
    $emailaddr   = trim($_POST['emailaddr'] ?? '');
    $phoneno     = trim($_POST['phoneno'] ?? '');
    $companyname = trim($_POST['companyname'] ?? '');
    $jobtitle    = trim($_POST['jobtitle'] ?? '');
    $streetadd   = trim($_POST['streetadd'] ?? '');
    $city        = trim($_POST['city'] ?? '');
    $state       = trim($_POST['state'] ?? '');
    $postal      = trim($_POST['postal'] ?? '');
    $country     = trim($_POST['country'] ?? '');

    // Simple validation (adjust as needed)
    if (!empty($firstname) && !empty($companyname) && !empty($phoneno)) {
        try {
            // Prepare SQL statement
            $sql = "INSERT INTO customer_info 
                    (firstname, lastname, emailaddr, phoneno, companyname, jobtitle, streetadd, city, state, postal, country)
                    VALUES 
                    (:firstname, :lastname, :emailaddr, :phoneno, :companyname, :jobtitle, :streetadd, :city, :state, :postal, :country)";
            
            $stmt = $pdo->prepare($sql);

            // Bind parameters
            $stmt->bindParam(':firstname', $firstname);
            $stmt->bindParam(':lastname', $lastname);
            $stmt->bindParam(':emailaddr', $emailaddr);
            $stmt->bindParam(':phoneno', $phoneno);
            $stmt->bindParam(':companyname', $companyname);
            $stmt->bindParam(':jobtitle', $jobtitle);
            $stmt->bindParam(':streetadd', $streetadd);
            $stmt->bindParam(':city', $city);
            $stmt->bindParam(':state', $state);
            $stmt->bindParam(':postal', $postal);
            $stmt->bindParam(':country', $country);

            // Execute statement
            if ($stmt->execute()) {
                echo "<p style='color:green;'>Customer added successfully!</p>";
                // Optional redirect
                // header("Location: your_form_page.php");
                // exit;
            } else {
                echo "<p style='color:red;'>Error saving customer. Please try again.</p>";
            }
        } catch (PDOException $e) {
            echo "Database error: " . $e->getMessage();
        }
    } else {
        echo "<p style='color:red;'>Please fill in all required fields.</p>";
    }
}
?>
