<?php
session_start();
include(__DIR__ . '/../config.php');

$cart = $_SESSION['cart'];

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$total = $_POST['total'];

try {

    // SAVE ORDER
    $stmt = $pdo->prepare("INSERT INTO orders (customer_name, customer_email, customer_phone, total) VALUES (?,?,?,?)");
    $stmt->execute([$name, $email, $phone, $total]);

    $order_id = $pdo->lastInsertId();

    $message = "New Order\n\n";
    $message .= "Name: $name\nPhone: $phone\n\n";

    // SAVE ITEMS
    foreach($cart as $id => $qty){

        $stmt = $pdo->prepare("SELECT * FROM products WHERE id=?");
        $stmt->execute([$id]);
        $p = $stmt->fetch();

        $stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?,?,?,?)");
        $stmt->execute([$order_id, $id, $qty, $p['price']]);

        $message .= $p['name']." x ".$qty."\n";
    }

    // SEND EMAIL
    $to = "yourcompany@email.com";
    $subject = "New Order #$order_id";
    $headers = "From: noreply@yourwebsite.com";

    mail($to, $subject, $message, $headers);

    unset($_SESSION['cart']);

    echo "<h3>Order placed successfully!</h3>";

} catch(Exception $e){
    echo "Error: " . $e->getMessage();
}