<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$businessName = trim($_POST['business_name'] ?? '');
$address = trim($_POST['address'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$email = trim($_POST['email'] ?? '');
$printerName = trim($_POST['printer_name'] ?? '');
$paperWidth = (int)($_POST['paper_width'] ?? 80);
$billType = (int)($_POST['bill_type'] ?? 1);

if ($businessName === '') {
    die('Business name is required.');
}

if ($paperWidth <= 0) {
    $paperWidth = 80;
}

if (!in_array($billType, [1, 2])) {
    $billType = 1;
}

/*
    Check existing settings
*/
$stmt = $db->prepare("
    SELECT id
    FROM settings
    LIMIT 1
");
$stmt->execute();

$existing = $stmt->fetch(PDO::FETCH_ASSOC);

if ($existing) {

    /*
        UPDATE
    */
    $stmt = $db->prepare("
        UPDATE settings
        SET
            business_name = ?,
            address = ?,
            phone = ?,
            email = ?,
            printer_name = ?,
            paper_width = ?,
            bill_type = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $businessName,
        $address,
        $phone,
        $email,
        $printerName,
        $paperWidth,
        $billType,
        $existing['id']
    ]);

} else {

    /*
        INSERT
    */
    $stmt = $db->prepare("
        INSERT INTO settings
        (
            business_name,
            address,
            phone,
            email,
            printer_name,
            paper_width,
            bill_type
        )
        VALUES
        (?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $businessName,
        $address,
        $phone,
        $email,
        $printerName,
        $paperWidth,
        $billType
    ]);
}

header('Location: index.php?saved=1');
exit;
?>