<?php
include 'config.php';
if(!isset($_SESSION['user_id'])) exit();

$agency_id = $_SESSION['agency_id'];
$name = $_POST['agency_name'];
$phone = $_POST['phone'];
$address = $_POST['address'];

// Handle Logo Upload
$logo_query = "";
if(!empty($_FILES['agency_logo']['name'])){
    $target_dir = "assets/logos/";
    if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
    
    $file_ext = pathinfo($_FILES["agency_logo"]["name"], PATHINFO_EXTENSION);
    $file_name = "logo_" . $agency_id . "_" . time() . "." . $file_ext;
    $target_file = $target_dir . $file_name;

    if(move_uploaded_file($_FILES["agency_logo"]["tmp_name"], $target_file)){
        $logo_query = ", logo_path = '$target_file'";
    }
}

$sql = "UPDATE agencies SET agency_name = ?, phone = ?, address = ? $logo_query WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssi", $name, $phone, $address, $agency_id);

if($stmt->execute()){
    header("Location: settings.php?success=1");
} else {
    echo "Error updating settings: " . $conn->error;
}
?>