<?php

session_start();
require_once __DIR__ . '/db.php';

$errors = [];

// Validate required fields
if (empty($_POST['org_name'])) {
    $errors['org_name'] = 'Organisation Name is required';
}
if (empty($_POST['location'])) {
    $errors['location'] = 'Business Location is required';
}
if (empty($_POST['industry'])) {
    $errors['industry'] = 'Industry is required';
}
if (empty($_POST['address1'])) {
    $errors['address1'] = 'Organisation Address is required';
}
if (empty($_POST['payroll'])) {
    $errors['payroll'] = 'Please select an option for payroll';
}

// If there are errors, store them in session and redirect back
if (!empty($errors)) {
    $_SESSION['org_errors'] = $errors;
    $_SESSION['org_old'] = $_POST;
    header("Location: organisation.php");
    exit;
}

// If validation passes, insert data
$name     = trim($_POST['org_name']);
$location = trim($_POST['location']);
$industry = trim($_POST['industry']);
$address1 = trim($_POST['address1']);
$address2 = trim($_POST['address2']);
$state    = trim($_POST['state']);
$city     = trim($_POST['city']);
$pincode  = trim($_POST['pincode']);
$payroll  = trim($_POST['payroll']);

// Prevent duplicate organisation names; if exists, reuse its ID
$check = $conn->prepare("SELECT id FROM organizations WHERE organisation_name = ? LIMIT 1");
$check->bind_param("s", $name);
$check->execute();
$check->bind_result($existingId);
if ($check->fetch()) {
    $_SESSION['org_id'] = $existingId;
    $_SESSION['org_name'] = $name;
    $_SESSION['user_company'] = $name;
    $check->close();
    header("Location: dashboard.php");
    exit;
}
$check->close();

$stmt = $conn->prepare("INSERT INTO organizations
    (organisation_name, business_location, industry, address_line1, address_line2, state, city, pincode, payroll_run)
    VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->bind_param(
    "sssssssss",
    $name,
    $location,
    $industry,
    $address1,
    $address2,
    $state,
    $city,
    $pincode,
    $payroll
);
$stmt->execute();
$newId = $stmt->insert_id;
$stmt->close();

// Store the new organisation ID for downstream use
$_SESSION['org_id'] = $newId;
$_SESSION['org_name'] = $name;
$_SESSION['user_company'] = $name;

header("Location: dashboard.php");

?>
