<?php
include 'db_connect.php';

if (isset($_POST['add_agency'])) {
    $agency_name = $_POST['agency_name'];
    $owner_name  = $_POST['owner_name'];
    $email       = $_POST['email'];
    $phone       = $_POST['phone'];
    $expiry_date = $_POST['expiry_date'];
    $password    = password_hash($_POST['password'], PASSWORD_DEFAULT);

    // 1. Insert into Agencies Table
    $stmt = $conn->prepare("INSERT INTO agencies (agency_name, owner_name, email, phone, expiry_date, status) VALUES (?, ?, ?, ?, ?, 'Active')");
    $stmt->bind_param("sssss", $agency_name, $owner_name, $email, $phone, $expiry_date);
    
    if ($stmt->execute()) {
        $new_agency_id = $conn->insert_id;

        // 2. Create the Agency Owner User Account
        $stmt_user = $conn->prepare("INSERT INTO users (agency_id, name, email, password, role) VALUES (?, ?, ?, ?, 'AgencyOwner')");
        $stmt_user->bind_param("isss", $new_agency_id, $owner_name, $email, $password);
        $stmt_user->execute();

        header("Location: manage_agencies.php?success=AgencyCreated");
    } else {
        echo "Error: " . $conn->error;
    }
}
?>