<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

require_once('../helper_functions/data_request.php');

if (!isset($_SESSION['userid'])) {
    sendJsonResponse(401, ["error" => "Unauthorized to access. Please login"]);
    exit;
}

$response = [];

try {
    ob_start();
    if (isset($_POST['getData'])) {
        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        $sql = "
            SELECT 
                st.id,
                st.subject,
                st.status,
                st.type,
                st.category,
                st.priority,
                st.description,
                st.created_at AS ticket_created_at,
                st.updated_at AS ticket_updated_at,
    
                CONCAT(owner.firstname, ' ', owner.lastname) AS owner_name,
                owner.email AS owner_email,
    
                CONCAT(createdBy.firstname, ' ', createdBy.lastname) AS created_by_name,
                createdBy.email AS created_by_email,
    
                p.name AS property_name
            FROM 
                support_tickets st
            LEFT JOIN 
                users owner ON st.owner = owner.id
            LEFT JOIN 
                users createdBy ON st.createdBy = createdBy.id
            LEFT JOIN 
                properties p ON st.property = p.id
            WHERE 
                st.property = :property_id
        ";
        
        $response = fetchDataWithJoins($sql, [':property_id' =>  $_POST['property_id']]);
        sendJsonResponse(200, $response);
        exit;
    }

    if (isset($_POST['getFilteredData'])) {
        $filters = $_POST;
        $sql = "SELECT st.id, st.subject, st.status, st.type, st.category, st.priority, st.description, st.created_at, st.updated_at, CONCAT(owner.firstname, ' ', owner.lastname) AS owner_name, owner.email AS owner_email, CONCAT(createdBy.firstname, ' ', createdBy.lastname) AS created_by_name, createdBy.email AS created_by_email, p.name AS property_name FROM support_tickets st LEFT JOIN users owner ON st.owner = owner.id LEFT JOIN users createdBy ON st.createdBy = createdBy.id LEFT JOIN properties p ON st.property = p.id WHERE 1";
        $params = [];
        $allowedFilters = ['status', 'type', 'category', 'priority', 'owner', 'property'];
        $conditions = [];
        foreach ($allowedFilters as $filter) {
            if (!empty($filters[$filter])) {
                $conditions[] = "st.$filter = :$filter";
                $params[":$filter"] = $filters[$filter];
            }
        }
        if (!empty($conditions)) $sql .= ' AND ' . implode(' AND ', $conditions);
        try {
            $filteredData = fetchDataWithJoins($sql, $params);
            sendJsonResponse(200, $filteredData);
            exit;
        } catch (Exception $e) {
            sendJsonResponse(500, ["error" => "Server error"]);
            exit;
        }
    }

    if (isset($_POST['saveTicketData'])) {
        $_POST['property'] = $_POST['property'] ?? $_SESSION['property_id'] ?? null;
        $keys = ['subject', 'status', 'type', 'category', 'priority','property_id', 'description', 'owner', 'property'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $data['createdBy'] = $_SESSION['userid'];
        $response = insertData('support_tickets', $data);
        sendJsonResponse(200, $response);
        exit;
    }

    if (isset($_POST['deleteSupportTicket'])) {
        $data = deleteData('support_tickets', 'id', $_POST['id']);
        $response = $data;
        sendJsonResponse(200, $response);
        exit;
    }

    if (isset($_POST['getTicketDataWithId'])) {
        $data = fetchDataWithId('support_tickets', $_POST['id']);
        $response = $data;
        sendJsonResponse(200, $response);
        exit;
    }

    if (isset($_POST['updateTicketData'])) {
        $formattedUpdatedAt = (new DateTime())->format('Y-m-d H:i:s');
        $keys = ['subject', 'type', 'category', 'priority', 'description', 'owner', 'property'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $data['createdBy'] = $_SESSION['userid'];
        $data['updated_at'] = $formattedUpdatedAt;
        if (isset($_POST['status']) && !empty($_POST['status'])) {
            $data['status'] = $_POST['status'];
        }
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('support_tickets', $data, $where, $params);
        $response = $updateSuccess;
        sendJsonResponse(200, $response);
        exit;
    }

    if (isset($_POST['updateTicketStatus'])) {
        $formattedUpdatedAt = (new DateTime())->format('Y-m-d H:i:s');
        $data['status'] = $_POST['status'];
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('support_tickets', $data, $where, $params);
        $response = $updateSuccess;
        sendJsonResponse(200, $response);
        exit;
    }

    if (isset($_POST['saveComment'])) {
        $keys = ['comment', 'ticketId'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $data['createdBy'] = $_SESSION['userid'];
        $response = insertData('ticketComments', $data);
        sendJsonResponse(200, $response);
        exit;
    }
} catch (Exception $e) {
    sendJsonResponse(500, ["error" => "Server error"]);
}
