<?php
require_once '../includes/auth.php';
require_once '../db.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
    exit;
}

$name   = trim($_POST['name'] ?? '');
$phone  = trim($_POST['phone'] ?? '');
$mobile = trim($_POST['mobile'] ?? '');
$gstin  = strtoupper(trim($_POST['gstin'] ?? ''));

if (!$name) {
    echo json_encode(['status' => 'error', 'message' => 'Vendor name is required']);
    exit;
}

// Derive state_code and state from GSTIN if provided
$state_code = '';
$state = '';
if (strlen($gstin) >= 2) {
    $gst_states = [
        '01'=>'Jammu & Kashmir','02'=>'Himachal Pradesh','03'=>'Punjab','04'=>'Chandigarh',
        '05'=>'Uttarakhand','06'=>'Haryana','07'=>'Delhi','08'=>'Rajasthan','09'=>'Uttar Pradesh',
        '10'=>'Bihar','11'=>'Sikkim','12'=>'Arunachal Pradesh','13'=>'Nagaland','14'=>'Manipur',
        '15'=>'Mizoram','16'=>'Tripura','17'=>'Meghalaya','18'=>'Assam','19'=>'West Bengal',
        '20'=>'Jharkhand','21'=>'Odisha','22'=>'Chhattisgarh','23'=>'Madhya Pradesh','24'=>'Gujarat',
        '26'=>'Dadra & Nagar Haveli','27'=>'Maharashtra','29'=>'Karnataka','30'=>'Goa',
        '31'=>'Lakshadweep','32'=>'Kerala','33'=>'Tamil Nadu','34'=>'Puducherry',
        '35'=>'Andaman & Nicobar Islands','36'=>'Telangana','37'=>'Andhra Pradesh',
        '38'=>'Ladakh','97'=>'Other Territory'
    ];
    $sc = substr($gstin, 0, 2);
    if (isset($gst_states[$sc])) {
        $state_code = $sc;
        $state = $gst_states[$sc];
    }
}

$stmt = $conn->prepare("
    INSERT INTO vendors (name, phone, mobile, gstin, state_code, state, status, company_id)
    VALUES (?, ?, ?, ?, ?, ?, 1, ?)
");
$stmt->bind_param("ssssssi", $name, $phone, $mobile, $gstin, $state_code, $state, $cid);

if ($stmt->execute()) {
    echo json_encode(['status' => 'ok', 'id' => $stmt->insert_id, 'name' => $name]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Database error']);
}
