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

$agency_id = $_SESSION['agency_id'];
$user_id = $_SESSION['user_id'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $agency_name = $_POST['agency_name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $email = $_POST['email'];
    $password = $_POST['password'];

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

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

    // 2. Update Agency Table
    $stmt1 = $conn->prepare("UPDATE agencies SET agency_name=?, phone=?, address=? $logo_sql WHERE id=?");
    $stmt1->bind_param("sssi", $agency_name, $phone, $address, $agency_id);
    $stmt1->execute();

    // 3. Update User Table (Security)
    if(!empty($password)) {
        $hashed_pass = password_hash($password, PASSWORD_DEFAULT);
        $stmt2 = $conn->prepare("UPDATE users SET email=?, password=? WHERE id=?");
        $stmt2->bind_param("ssi", $email, $hashed_pass, $user_id);
    } else {
        $stmt2 = $conn->prepare("UPDATE users SET email=? WHERE id=?");
        $stmt2->bind_param("si", $email, $user_id);
    }
    $stmt2->execute();

    header("Location: agency_profile.php?msg=success");
}
?>