<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$id = intval($_POST['id']);
$name = $_POST['company_name'];
$code = $_POST['company_code'];

// 1. Fetch current paths to handle file replacement
$curr = $conn->query("SELECT left_logo, right_logo FROM company WHERE id = $id")->fetch_assoc();

function handleUpload($fileKey, $oldPath) {
    if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] == 0) {
        // Delete old file if it exists
        if (!empty($oldPath) && file_exists("../../" . $oldPath)) { unlink("../../" . $oldPath); }

        $ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);
        $newName = "company_" . time() . "_" . $fileKey . "." . $ext;
        $target = "../../uploads/logos/" . $newName;
        
        if (move_uploaded_file($_FILES[$fileKey]['tmp_name'], $target)) {
            return "uploads/logos/" . $newName;
        }
    }
    return $oldPath;
}

$new_left = handleUpload('left_logo', $curr['left_logo']);
$new_right = handleUpload('right_logo', $curr['right_logo']);

// 2. Update Database
$sql = "UPDATE company SET company_name = ?, company_code = ?, left_logo = ?, right_logo = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssi", $name, $code, $new_left, $new_right, $id);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Company updated successfully!"]);
} else {
    echo json_encode(["success" => false, "message" => "Update failed: " . $conn->error]);
}