<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once('../../db.php');
include '../../shared/functionsinc.php';
include '../helper_functions/data_request.php';

if (isset($_SESSION['userid'])) {

    if (isset($_POST["submitneworg"])) {
        $orgName = $_POST["orgname"];
        $orgAddress = $_POST["orgaddress"];
        $orgCity = $_POST["orgcity"];
        $orgState = $_POST["orgstate"];
        $orgZip = $_POST["orgzip"];
        $orgContact = $_POST["orgcontact"];
        $orgContactPhone = preg_replace('/\D/', '', $_POST["orgcontactphone"]);
        $dealerId = $_SESSION['userid'];

        if ($_SESSION['layer'] === 'sub_dealer'){
            $dealerAssoc = fetchData('dealer_admins', ['id' => $_SESSION['userid']]);
            $dealerId = $dealerAssoc[0]['dealer_assoc'];
        }else {
            $dealerId = $_SESSION['userid'];
        }

        newOrganization($pdo, $orgName, $orgAddress, $orgCity, $orgState, $orgZip, $orgContact, $orgContactPhone, $dealerId);
        header( "Location: ../../dashboard.php?tab=my_properties" );
    }

    if (isset($_POST["getorg"])) {
        $userId = $_SESSION['userid'];
        $userLayer = $_SESSION['layer'];

        $organizations = getOrg($pdo, $userId, $userLayer);
        echo json_encode($organizations);
    }

    if (isset($_POST["editorg"])) {
        $orgid = $_POST["orgid"];
        $allOrgs = getOrg($pdo, $_SESSION['userid'], $_SESSION['layer']);
        $orgData['orgs'] = array_filter($allOrgs, function($org) use ($orgid) {
            return $org['id'] == $orgid;
        });
    
        $orgData['orgs'] = array_values($orgData);
        $orgData['orgs'] = count($orgData['orgs']) > 0 ? $orgData['orgs'][0] : null;
        $orgData['dealers'] = getDealers($pdo, $_SESSION['userid'], $_SESSION['layer']);
        
        if ($orgData) {
            echo json_encode($orgData);
        } else {
            echo json_encode(['error' => 'Organization not found']);
        }
        exit();
    }

    if (isset($_POST["uupdateorg"])) {

        $orgId = $_POST['idstore'];
        $orgName = $_POST['uorgname'];
        $orgAddress = $_POST['uorgaddress'];
        $orgCity = $_POST['uorgcity'];
        $orgState = $_POST['uorgstate'];
        $orgZip = $_POST['uorgzip'];
        $orgContact = $_POST['uorgcontact'];
        $orgContactPhone = preg_replace('/\D/', '', $_POST['uorgcontactphone']);
        $orgdealer = $_POST['udealerid'];

        $updateStatus = updateOrganization($pdo, $orgId, $orgName, $orgAddress, $orgCity, $orgState, $orgZip, $orgContact, $orgContactPhone, $orgdealer);
    
        $message = "";
        $alertType = "";

        switch ($updateStatus) {
            case false:
                $_SESSION['alert'] = [
                    "message" => "Failed to update Organization!",
                    "type" => "danger"
                ];
                break;
            case true:
                $_SESSION['alert'] = [
                    "message" => "Organization updated successfully!",
                    "type" => "success"
                ];
                break;
            default:
                break;
        }
        header( "Location: ../../dashboard.php?tab=my_properties" );
        exit();
    }
} else {
    header("location: ../../login.php");
    exit();
}
?>

