<?php

class PermitsBySubdivision extends Base {

    // Variables

    private $current_user_serial = 0;
    private $current_user_id = "";
    private $current_user_name = "";
    private $current_user_email = "";
    private $pagination_size = 20;
    private $pagination_page = 1;

    // =================
    // Class Constructor
    // =================

    public function __construct() {

        set_error_handler(array($this, "displayError"));

        date_default_timezone_set(self::TIMEZONE);

        $this->current_user_serial = $_SESSION[self::USER_SERIAL] ?? 0;
        $this->current_user_id = $_SESSION[self::USER_ID] ?? "";
        $this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
        $this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";

        $this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
    }

    // ==============
    // Search Permits
    // ==============

    public function searchPermits($subscription_serial = 0) {

        $subscription_serial = filter_input(INPUT_POST, "subscription_serial") ?: $subscription_serial;

        $subscription = (new Subscriptions())->getSubscription($subscription_serial);

        if ($subscription->count() == 0) {
            $this->logError("Invalid Subscription ({$subscription_serial}). " . __METHOD__);
        }

        $permit_area = $subscription->record->subscription_area;
        $projecttype = $subscription->record->subscription_projecttype;

        $permits = $this->getPermits($permit_area, $projecttype);

        $counties = (new Counties())->getCountiesByArea($permit_area);
        $popovers = (new Popovers())->getPopovers();

        $XML = $this->mergeXML($permits, "<XML/>");
        $XML = $this->mergeXML($counties, $XML);
        $XML = $this->mergeXML($subscription, $XML);
        $XML = $this->mergeXML($popovers, $XML);

        $content = $this->applyXSL($XML, $this->getXSL("searchPermitsBySubdivision"));
        $this->displayContent($content);
    }

    public function getPermits($permit_area, $projecttype) {

        $rdi_county_raw = trim(filter_input(INPUT_POST, "rdi_county") ?: "");
        $rdi_and_or = trim(filter_input(INPUT_POST, "rdi_and_or") ?: "OR");
        $rdi_company = trim(filter_input(INPUT_POST, "rdi_company") ?: "");
        $rdi_sub_div_name = trim(filter_input(INPUT_POST, "rdi_sub_div_name") ?: "");
        $rdi_project_city = trim(filter_input(INPUT_POST, "rdi_project_city") ?: "");
        $rdi_project_addr = trim(filter_input(INPUT_POST, "rdi_project_addr") ?: "");

        $rdi_entry_start_date = filter_input(INPUT_POST, "rdi_entry_start_date") ?: "";
        $rdi_entry_end_date = filter_input(INPUT_POST, "rdi_entry_end_date") ?: "";
        $rdi_permit_start_date = filter_input(INPUT_POST, "rdi_permit_start_date") ?: "";
        $rdi_permit_end_date = filter_input(INPUT_POST, "rdi_permit_end_date") ?: "";

        $pagination = filter_input(INPUT_POST, "pagination") ?: "";

        // Normalize dates to Y-m-d or null
        $rdi_entry_start_date = ($rdi_entry_start_date === "") ? null : date("Y-m-d", strtotime($rdi_entry_start_date));
        $rdi_entry_end_date = ($rdi_entry_end_date === "") ? null : date("Y-m-d", strtotime($rdi_entry_end_date));
        $rdi_permit_start_date = ($rdi_permit_start_date === "") ? null : date("Y-m-d", strtotime($rdi_permit_start_date));
        $rdi_permit_end_date = ($rdi_permit_end_date === "") ? null : date("Y-m-d", strtotime($rdi_permit_end_date));

        // Validate AND/OR
        if (!in_array(strtoupper($rdi_and_or), ["AND", "OR"], true)) {
            $rdi_and_or = "OR";
        }

        // Pagination / ordering
        $this->pagination_size = filter_input(INPUT_POST, "rdis_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
        $rdis_order_by = filter_input(INPUT_POST, "rdis_order_by") ?: "rdi_permit_number";
        $rdis_order_direction = filter_input(INPUT_POST, "rdis_order_direction" ?? "DESC");

        $allowed_order_columns = [
            "rdi_permit_number",
            "rdi_county", "rdi_sub_div_name", "rdi_project_addr", "rdi_city",
            "rdi_state", "rdi_zip", "rdi_company", "rdi_permit_date", "rdi_size", "rdi_value"
        ];

        if (!in_array($rdis_order_by, $allowed_order_columns, true)) {
            $rdis_order_by = "rdi_sub_div_name";
        }
        if (!in_array(strtoupper((string) $rdis_order_direction), ["ASC", "DESC"], true)) {
            $rdis_order_direction = "DESC";
        }

        // Database Connection
        $connection = $this->connect();

        // -------- County clause (shared) --------
        // Parse "1,12" -> [1,12], keep only digits, cast to int
        $countyIds = array_values(array_filter(
                        array_map(
                                fn($v) => ctype_digit(trim($v)) ? (int) trim($v) : null,
                                explode(",", $rdi_county_raw)
                        ),
                        fn($v) => $v !== null
                ));

        $countyClauseCount = "";
        $countyClauseData = "";
        $countyParams = [];  // [':county_0' => 1, ':county_1' => 12]
        $bindArea = false;

        if (!empty($countyIds)) {
            if (count($countyIds) === 1) {
                $countyClauseCount = " and rdi_county = :county_0";
                $countyClauseData = " and view_rdis.rdi_county = :county_0";
                $countyParams[':county_0'] = $countyIds[0];
            } else {
                $ph = [];
                foreach ($countyIds as $i => $id) {
                    $k = ":county_$i";
                    $ph[] = $k;
                    $countyParams[$k] = $id;
                }
                $in = implode(",", $ph);
                $countyClauseCount = " and rdi_county in ($in)";
                $countyClauseData = " and view_rdis.rdi_county in ($in)";
            }
        } elseif ($permit_area != "All") {
            $countyClauseCount = " and rdi_county in (select county_serial from view_counties where county_area = :permit_area)";
            $countyClauseData = " and view_rdis.rdi_county in (select county_serial from view_counties where county_area = :permit_area)";
            $bindArea = true;
        } else {
            // No county/area filter -> omit entirely to keep the plan simple
            $countyClauseCount = "";
            $countyClauseData = "";
        }

        // ===================== COUNT QUERY =====================
        $SQL = "select count(*) as count
                  from view_rdis
                 where rdi_project_type = :rdi_project_type
                 $countyClauseCount ";

        if (!empty($rdi_company)) {
            $SQL .= " and rdi_company like :rdi_company";
        }

        if (!empty($rdi_sub_div_name)) {
            $SQL .= " and rdi_sub_div_name like :rdi_sub_div_name";
        }

        if (!empty($rdi_project_city)) {
            $SQL .= " and rdi_project_city like :rdi_project_city";
        }

        if (!empty($rdi_project_addr)) {
            $SQL .= " and rdi_project_addr like :rdi_project_addr";
        }

        // group date conditions so $rdi_and_or applies between themcx

        $dateConds = [];

        if ($rdi_entry_start_date && $rdi_entry_end_date) {
            $dateConds[] = "(rdi_entry_date between :rdi_entry_start_date and :rdi_entry_end_date)";
        } elseif ($rdi_entry_start_date) {
            $dateConds[] = "(rdi_entry_date >= :rdi_entry_start_date)";
        }
        if ($rdi_permit_start_date && $rdi_permit_end_date) {
            $dateConds[] = "(rdi_permit_date between :rdi_permit_start_date and :rdi_permit_end_date)";
        } elseif ($rdi_permit_start_date) {
            $dateConds[] = "(rdi_permit_date >= :rdi_permit_start_date)";
        }
        if ($dateConds) {
            $SQL .= " and (" . implode(" $rdi_and_or ", $dateConds) . ")";
        }

        $statement = $connection->prepare($SQL);

        $statement->bindValue(":rdi_project_type", $projecttype, PDO::PARAM_STR);

        foreach ($countyParams as $k => $v) {
            $statement->bindValue($k, $v, PDO::PARAM_INT);
        }

        if ($bindArea) {
            $statement->bindValue(":permit_area", $permit_area, PDO::PARAM_STR);
        }
        if (!empty($rdi_company)) {
            $statement->bindValue(":rdi_company", '%' . $rdi_company . '%', PDO::PARAM_STR);
        }
        if (!empty($rdi_sub_div_name)) {
            $statement->bindValue(":rdi_sub_div_name", '%' . $rdi_sub_div_name . '%', PDO::PARAM_STR);
        }
        if (!empty($rdi_project_city)) {
            $statement->bindValue(":rdi_project_city", '%' . $rdi_project_city . '%', PDO::PARAM_STR);
        }
        if (!empty($rdi_project_addr)) {
            $statement->bindValue(":rdi_project_addr", '%' . $rdi_project_addr . '%', PDO::PARAM_STR);
        }
        if ($rdi_entry_start_date) {
            $statement->bindValue(":rdi_entry_start_date", $rdi_entry_start_date);
        }
        if ($rdi_entry_end_date && str_contains($SQL, ":rdi_entry_end_date")) {
            $statement->bindValue(":rdi_entry_end_date", $rdi_entry_end_date);
        }
        if ($rdi_permit_start_date) {
            $statement->bindValue(":rdi_permit_start_date", $rdi_permit_start_date);
        }
        if ($rdi_permit_end_date && str_contains($SQL, ":rdi_permit_end_date")) {
            $statement->bindValue(":rdi_permit_end_date", $rdi_permit_end_date);
        }

        $statement->execute();

        $recordset = $statement->fetch(PDO::FETCH_ASSOC);

        $count = $recordset ? (int) $recordset["count"] : 0;

        // -------- Pagination --------

        switch ($pagination) {
            case "first": $this->pagination_page = 1;
                break;
            case "previous": $this->pagination_page = max($this->pagination_page - 1, 1);
                break;
            case "next": $this->pagination_page = min($this->pagination_page + 1, (int) ceil($count / $this->pagination_size));
                break;
            case "last": $this->pagination_page = (int) ceil($count / $this->pagination_size);
                break;
        }

        $offset = max(0, ($this->pagination_page - 1) * $this->pagination_size);
        $start = $offset + 1;
        $end = min($count, $start + $this->pagination_size - 1);

        // ===================== DATA QUERY =====================
        $SQL = "select view_rdis.*
                  from view_rdis
                 where view_rdis.rdi_project_type = :rdi_project_type
                   $countyClauseData";

        if (!empty($rdi_company)) {
            $SQL .= " and view_rdis.rdi_company like :rdi_company";
        }

        if (!empty($rdi_sub_div_name)) {
            $SQL .= " and view_rdis.rdi_sub_div_name like :rdi_sub_div_name";
        }

        if (!empty($rdi_project_city)) {
            $SQL .= " and view_rdis.rdi_project_city like :rdi_project_city";
        }

        if (!empty($rdi_project_addr)) {
            $SQL .= " and view_rdis.rdi_project_addr like :rdi_project_addr";
        }

        $dateConds = [];
        if ($rdi_entry_start_date && $rdi_entry_end_date) {
            $dateConds[] = "(view_rdis.rdi_entry_date between :rdi_entry_start_date and :rdi_entry_end_date)";
        } elseif ($rdi_entry_start_date) {
            $dateConds[] = "(view_rdis.rdi_entry_date >= :rdi_entry_start_date)";
        }
        if ($rdi_permit_start_date && $rdi_permit_end_date) {
            $dateConds[] = "(view_rdis.rdi_permit_date between :rdi_permit_start_date and :rdi_permit_end_date)";
        } elseif ($rdi_permit_start_date) {
            $dateConds[] = "(view_rdis.rdi_permit_date >= :rdi_permit_start_date)";
        }
        if ($dateConds) {
            $SQL .= " and (" . implode(" $rdi_and_or ", $dateConds) . ")";
        }

        $SQL .= " order by $rdis_order_by $rdis_order_direction
                     limit :limit
                    offset :offset";

        $statement = $connection->prepare($SQL);

        $statement->bindValue(":rdi_project_type", $projecttype, PDO::PARAM_STR);

        foreach ($countyParams as $k => $v) {
            $statement->bindValue($k, $v, PDO::PARAM_INT);
        }

        if ($bindArea) {
            $statement->bindValue(":permit_area", $permit_area, PDO::PARAM_STR);
        }
        if (!empty($rdi_company)) {
            $statement->bindValue(":rdi_company", '%' . $rdi_company . '%', PDO::PARAM_STR);
        }
        if (!empty($rdi_sub_div_name)) {
            $statement->bindValue(":rdi_sub_div_name", '%' . $rdi_sub_div_name . '%', PDO::PARAM_STR);
        }
        if (!empty($rdi_project_city)) {
            $statement->bindValue(":rdi_project_city", '%' . $rdi_project_city . '%', PDO::PARAM_STR);
        }
        if (!empty($rdi_project_addr)) {
            $statement->bindValue(":rdi_project_addr", '%' . $rdi_project_addr . '%', PDO::PARAM_STR);
        }
        if ($rdi_entry_start_date) {
            $statement->bindValue(":rdi_entry_start_date", $rdi_entry_start_date);
        }
        if ($rdi_entry_end_date && str_contains($SQL, ":rdi_entry_end_date")) {
            $statement->bindValue(":rdi_entry_end_date", $rdi_entry_end_date);
        }
        if ($rdi_permit_start_date) {
            $statement->bindValue(":rdi_permit_start_date", $rdi_permit_start_date);
        }
        if ($rdi_permit_end_date && str_contains($SQL, ":rdi_permit_end_date")) {
            $statement->bindValue(":rdi_permit_end_date", $rdi_permit_end_date);
        }
        $statement->bindValue(":limit", $this->pagination_size, PDO::PARAM_INT);
        $statement->bindValue(":offset", $offset, PDO::PARAM_INT);

        $statement->execute();

        $rdis = $this->getTableXML("rdis", $statement);

        foreach ($rdis as $rdi) {
            if (!empty($rdi->rdi_county)) {
                $county = (new Counties())->getCounty($rdi->rdi_county);
                $rdi->rdi_county_name_verbose = $county->record->county_name ?? null;
            }
        }

        // Pagination attributes
        $rdis->addAttribute("count", $count);
        $rdis->addAttribute("start", $start);
        $rdis->addAttribute("end", $end);
        $rdis->addAttribute("page", $this->pagination_page);
        $_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;

        return $rdis;
    }

    // =============================
    // Fetch All Permits for Exports
    // =============================

    public function getAllPermitsBySubDivision($permit_area, $projecttype) {

        $connection = $this->connect();

        // Count Query
        $SQL = "select count(*) as count
                  from view_rdis r 
                  join counties c on r.rdi_county = c.county_serial 
                 where r.rdi_project_type = :rdi_project_type 
                   and r.rdi_county in 
                        (select county_serial 
                           from view_counties 
                          where county_area = :permit_area)";

        $statement = $connection->prepare($SQL);

        $statement->bindValue(":rdi_project_type", $projecttype, PDO::PARAM_STR);
        $statement->bindValue(":permit_area", $permit_area, PDO::PARAM_STR);

        $statement->execute();
        $recordset = $statement->fetch(PDO::FETCH_ASSOC);
        $count = $recordset ? (int) $recordset["count"] : 0;

        // === DATA QUERY ===
        $SQL = "select r.*, c.county_name as rdi_county_name_verbose 
                  from view_rdis r 
                  join counties c on r.rdi_county = c.county_serial 
                 where r.rdi_project_type = :rdi_project_type 
                   and r.rdi_county in 
                        (select county_serial 
                           from view_counties 
                          where county_area = :permit_area)";

        $statement = $connection->prepare($SQL);

        $statement->bindValue(":rdi_project_type", $projecttype, PDO::PARAM_STR);
        $statement->bindValue(":permit_area", $permit_area, PDO::PARAM_STR);

        $statement->execute();

        $rdis = $this->getTableXML("rdis", $statement);

        // Insert Pagination Attributes
        $rdis->addAttribute("count", $count);

        return $rdis;
    }

    // ======================
    // Return a Permit Object
    // ======================

    public function getSelectedPermits($permits = array()) {

        if (empty($permits)) {
            return;
        }

        $SQL = "select view_rdis.* from view_rdis where rdi_serial in ({$permits})";

        return $this->getTable("permits", $SQL);
    }

    // ================================
    // Return AutoComplete Names (ajax)
    // ================================

    public function getAutoCompleteSubdivisions() {

        $results = array();

        $subdivision = filter_input(INPUT_GET, "rdi_sub_div_name") ?: "";
        $subdivision = trim(preg_replace("/\s+/", " ", $subdivision));
        $subdivision = preg_replace("/'+/", "'", $subdivision);
        $subdivision = preg_replace('/"+/', '"', $subdivision);
        $subdivision = str_replace("'", "''", $subdivision);

        $SQL = "select distinct rdi_sub_div_name from view_rdis where rdi_sub_div_name like '%{$subdivision}%' order by rdi_sub_div_name limit 10 offset 0";

        $matches = $this->getTable("subdivisions", $SQL);

        foreach ($matches as $match) {
            $results[] = (string) $match->rdi_sub_div_name;
        }

        header('Content-Type: application/json');
        echo json_encode($results);
        exit();
    }

    // ================================
    // Return AutoComplete Names (ajax)
    // ================================

    public function getAutoCompleteCities() {

        $results = array();

        $city = filter_input(INPUT_GET, "rdi_project_city") ?: "";
        $city = trim(preg_replace("/\s+/", " ", $city));
        $city = preg_replace("/'+/", "'", $city);
        $city = preg_replace('/"+/', '"', $city);
        $city = str_replace("'", "''", $city);

        $SQL = "select distinct rdi_project_city from view_rdis where rdi_project_city like '%{$city}%' order by rdi_project_city limit 10 offset 0";

        $matches = $this->getTable("cities", $SQL);

        foreach ($matches as $match) {
            $results[] = (string) $match->rdi_project_city;
        }

        header('Content-Type: application/json');
        echo json_encode($results);
        exit();
    }

    // ================================
    // Return AutoComplete Names (ajax)
    // ================================

    public function getAutoCompleteStreets() {

        $results = array();

        $street = filter_input(INPUT_GET, "rdi_project_addr") ?: "";
        $street = trim(preg_replace("/\s+/", " ", $street));
        $street = preg_replace("/'+/", "'", $street);
        $street = preg_replace('/"+/', '"', $street);
        $street = str_replace("'", "''", $street);

        $SQL = "select distinct rdi_project_addr from view_rdis where rdi_project_addr like '%{$street}%' order by rdi_project_addr limit 10 offset 0";

        $matches = $this->getTable("cities", $SQL);

        foreach ($matches as $match) {
            $results[] = (string) $match->rdi_project_addr;
        }

        header('Content-Type: application/json');
        echo json_encode($results);
        exit();
    }

    // ======================
    // Return a Permit Object
    // ======================

    public function getPermit($rdi_serial = 0) {

        $SQL = "select view_rdis.* from view_rdis where rdi_serial = {$rdi_serial}";

        return $this->getTable("permit", $SQL);
    }

    // =============================
    // Return a Permit Record Dialog
    // =============================

    public function getPermitRecordDialog() {

        $rdi_serial = filter_input(INPUT_POST, "rdi_serial", FILTER_SANITIZE_NUMBER_INT) ?: 9;

        $permit_record = $this->getPermit($rdi_serial);

        $rdi_county = (new Counties())->getCounty($permit_record->record->rdi_county);
        $permit_record->record->rdi_county = $rdi_county->record->county_name;

        $content = $this->applyXSL($permit_record, $this->getXSL("permitRecordDialog"));

        if ($_SESSION[self::AJAX]) {
            echo $content;
        } else {
            $this->displayContentPage($content);
        }
    }
}

?>
