<?php
header("Content-Type: application/json");

ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'config/koneksi.php';

$input = json_decode(file_get_contents("php://input"), true);

/// =========================
/// 🔥 AMBIL DATA
/// =========================
$user_id = $input['user_id'] ?? '';
$name    = trim($input['name'] ?? '');
$phone   = trim($input['phone'] ?? '');
$address = trim($input['address'] ?? '');

/// =========================
/// 🔥 VALIDASI
/// =========================
if ($user_id === '' || $name === '') {
    echo json_encode([
        "success" => false,
        "message" => "User ID & Nama perusahaan wajib"
    ]);
    exit;
}

$now = date("Y-m-d H:i:s");

/// =========================
/// 🔥 CEK USER ADA?
/// =========================
$stmt = $conn->prepare("SELECT id, company_id FROM users WHERE id = ? LIMIT 1");

if (!$stmt) {
    echo json_encode([
        "success" => false,
        "message" => "Prepare gagal",
        "error" => $conn->error
    ]);
    exit;
}

$stmt->bind_param("s", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    echo json_encode([
        "success" => false,
        "message" => "User tidak ditemukan"
    ]);
    exit;
}

/// =========================
/// 🔥 CEK SUDAH PUNYA COMPANY?
/// =========================
if (!empty($user['company_id'])) {
    echo json_encode([
        "success" => true,
        "message" => "User sudah punya company",
        "company_id" => $user['company_id'],
        "warehouse_id" => null
    ]);
    exit;
}

/// =========================
/// 🔥 TRANSACTION
/// =========================
$conn->begin_transaction();

try {

 
$company_id = uniqid("cmp_");

date_default_timezone_set('Asia/Jakarta');

$now = date("Y-m-d H:i:s");


$expired_at = date("Y-m-d 23:59:59", strtotime("+7 days"));

$stmt = $conn->prepare("
    INSERT INTO companies (
        id, name, phone, address, expired_at, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?)
");

if (!$stmt) throw new Exception($conn->error);

$stmt->bind_param(
    "sssssss",
    $company_id,
    $name,
    $phone,
    $address,
    $expired_at,
    $now,
    $now
);

    if (!$stmt->execute()) throw new Exception($stmt->error);


    /// =========================
    /// 🔥 CREATE WAREHOUSE
    /// =========================
    $warehouse_id = uniqid("wh_");

    $stmt = $conn->prepare("
        INSERT INTO warehouses (
            id, company_id, name, type, created_at, updated_at
        ) VALUES (?, ?, 'Gudang Utama', 'main', ?, ?)
    ");

    if (!$stmt) throw new Exception($conn->error);

    $stmt->bind_param(
        "ssss",
        $warehouse_id,
        $company_id,
        $now,
        $now
    );

    if (!$stmt->execute()) throw new Exception($stmt->error);


    /// =========================
    /// 🔥 UPDATE USER
    /// =========================
    $stmt = $conn->prepare("
        UPDATE users 
        SET company_id = ?, warehouse_id = ?, updated_at = ?
        WHERE id = ?
    ");

    if (!$stmt) throw new Exception($conn->error);

    $stmt->bind_param(
        "ssss",
        $company_id,
        $warehouse_id,
        $now,
        $user_id
    );

    if (!$stmt->execute()) throw new Exception($stmt->error);


    /// =========================
    /// 🔥 COMMIT
    /// =========================
    $conn->commit();

    echo json_encode([
        "success" => true,
        "company_id" => $company_id,
        "warehouse_id" => $warehouse_id
    ]);

} catch (Exception $e) {

    $conn->rollback();

    echo json_encode([
        "success" => false,
        "message" => "Gagal create company",
        "error" => $e->getMessage()
    ]);
}