<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../app/Config/config.php';
require_once __DIR__ . '/../../../app/Config/functions.php';
require_once __DIR__ . '/../../../app/Models/Vendor.php';

require_login();

header('Content-Type: application/json');

try {
    $name           = trim($_POST['name'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $phone          = trim($_POST['phone'] ?? '');
    $email          = trim($_POST['email'] ?? '');
    $address        = trim($_POST['address'] ?? '');
    $gst_no         = trim($_POST['gst_no'] ?? '');

    if ($name === '') {
        throw new Exception('Vendor name is required.');
    }

    $model = new Vendor();
    $success = $model->create([
        'name'           => $name,
        'contact_person' => $contact_person,
        'phone'          => $phone,
        'email'          => $email,
        'address'        => $address,
        'gst_no'         => $gst_no
    ]);

    echo json_encode([
        'status'  => $success ? 'success' : 'error',
        'message' => $success ? 'Vendor added successfully.' : 'Failed to add vendor.'
    ]);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
