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

// Basic validation
if (empty($_POST['supplier_name'])) {
    $_SESSION['flash']['supplier_error'] = "Supplier name is required.";
    header("Location: ../pages/admin/add_supplier.php");
    exit;
}

// Sanitize inputs
$supplier_name   = trim($_POST['supplier_name']);
$contact_person  = trim($_POST['contact_person']);
$phone           = trim($_POST['phone']);
$email           = trim($_POST['email']);
$address         = trim($_POST['address']);
$t_pin           = trim($_POST['t_pin']);

try {
    $stmt = $conn->prepare("
        INSERT INTO suppliers (supplier_name, contact_person, phone, email, address, t_pin)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        throw new Exception("Failed to prepare statement: " . $conn->error);
    }

    $stmt->bind_param("ssssss", 
        $supplier_name,
        $contact_person,
        $phone,
        $email,
        $address,
        $t_pin
    );

    if ($stmt->execute()) {
        $_SESSION['flash']['supplier_success'] = "Supplier added successfully.";
        header("Location: ../pages/admin/suppliers.php");
        exit;
    } else {
        throw new Exception("Failed to insert supplier: " . $stmt->error);
    }

} catch (Exception $e) {
    $_SESSION['flash']['supplier_error'] = $e->getMessage();
    header("Location: ../pages/admin/add_supplier.php");
    exit;
}
