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

// 🔒 MATIKAN HTML ERROR
error_reporting(E_ALL);
ini_set('display_errors', 0);

// 🔥 ERROR → JSON
set_error_handler(function ($severity, $message, $file, $line) {
    echo json_encode([
        "success" => false,
        "message" => "PHP Error: $message"
    ]);
    exit;
});

require_once __DIR__ . '/config/koneksi.php';
require_once __DIR__ . '/config/jwt.php';

// ================= TOKEN =================
function getAuthHeader() {
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        return $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        return $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } elseif (function_exists('getallheaders')) {
        $headers = getallheaders();
        return $headers['Authorization'] ?? $headers['authorization'] ?? '';
    }
    return '';
}

$auth = getAuthHeader();

if (!$auth) {
    echo json_encode(["success"=>false,"message"=>"Unauthorized"]);
    exit;
}

$token = str_replace("Bearer ", "", $auth);
$userData = verifyJWT($token);

if (!$userData) {
    echo json_encode(["success"=>false,"message"=>"Token invalid"]);
    exit;
}

$companyId = $userData['company_id'] ?? null;

if (!$companyId) {
    echo json_encode(["success"=>false,"message"=>"Company tidak valid"]);
    exit;
}

// ================= VALIDASI =================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "success" => false,
        "message" => "Method harus POST"
    ]);
    exit;
}

if (empty($_POST) && empty($_FILES)) {
    echo json_encode([
        "success" => false,
        "message" => "Format request tidak terbaca"
    ]);
    exit;
}

// ================= INPUT =================
$name = $_POST['name'] ?? '';
$phone = $_POST['phone'] ?? '';
$address = $_POST['address'] ?? '';

if (!$name) {
    echo json_encode(["success"=>false,"message"=>"Nama wajib"]);
    exit;
}

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

// ================= AMBIL LOGO LAMA =================
$oldLogo = null;

$get = $conn->prepare("SELECT logo FROM companies WHERE id=?");
if ($get) {
    $get->bind_param("s", $companyId);
    $get->execute();
    $res = $get->get_result();
    $row = $res->fetch_assoc();
    $oldLogo = $row['logo'] ?? null;
}

// ================= UPLOAD + COMPRESS =================
$logoPath = null;

if (isset($_FILES['logo']) && $_FILES['logo']['error'] === 0) {

    $dir = __DIR__ . "/uploads/company/";

    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }

    $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
    if (!$ext) $ext = "jpg";

    $filename = "logo_" . time() . "." . $ext;
    $fullPath = $dir . $filename;

    // 🔥 LOAD IMAGE
    $tmp = $_FILES['logo']['tmp_name'];

 $tmp = $_FILES['logo']['tmp_name'];

$info = getimagesize($tmp);

if (!$info) {
    echo json_encode([
        "success" => false,
        "message" => "File bukan gambar valid"
    ]);
    exit;
}

$mime = $info['mime'];

switch ($mime) {
    case 'image/jpeg':
        $image = imagecreatefromjpeg($tmp);
        break;

    case 'image/png':
        $image = imagecreatefrompng($tmp);
        break;

    case 'image/webp':
        $image = imagecreatefromwebp($tmp);
        break;

    default:
        echo json_encode([
            "success" => false,
            "message" => "Format gambar tidak didukung ($mime)"
        ]);
        exit;
}

    if (!$image) {
        echo json_encode([
            "success" => false,
            "message" => "Gagal membaca gambar"
        ]);
        exit;
    }

    // 🔥 COMPRESS (JPEG QUALITY 70)
    imagejpeg($image, $fullPath, 70);
    imagedestroy($image);

    // 🔥 HAPUS LOGO LAMA
    if ($oldLogo && file_exists(__DIR__ . "/" . $oldLogo)) {
        unlink(__DIR__ . "/" . $oldLogo);
    }

    $logoPath = "uploads/company/" . $filename;
}

// ================= UPDATE =================
if ($logoPath) {
    $stmt = $conn->prepare("
        UPDATE companies 
        SET name=?, phone=?, address=?, logo=?, updated_at=? 
        WHERE id=?
    ");

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

    $stmt->bind_param("ssssss", $name, $phone, $address, $logoPath, $now, $companyId);

} else {
    $stmt = $conn->prepare("
        UPDATE companies 
        SET name=?, phone=?, address=?, updated_at=? 
        WHERE id=?
    ");

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

    $stmt->bind_param("sssss", $name, $phone, $address, $now, $companyId);
}

// ================= EXECUTE =================
if (!$stmt->execute()) {
    echo json_encode([
        "success" => false,
        "message" => $stmt->error
    ]);
    exit;
}

// ================= RESPONSE =================
echo json_encode([
    "success" => true,
    "message" => "Company berhasil diupdate",
    "logo" => $logoPath
]);