<?php

class Notes
{
    private $db_con;

    public function __construct()
    {
        global $con;
        $this->db_con = $con;
    }

    public function listing($input_data): array
    {
        // error_reporting(E_ALL);
        // ini_set('display_errors', '1');

        $output_message = new OutputMessage();
        $where = [
            "a.is_deleted = 0",
            "a.is_archived = 0",
        ];

        $result = $this->generic_list($where);
        if($result && count($result) > 0){
            $api_output = $output_message->successOutput(["list" => $result], 'All notes loaded');
        } else {
            $api_output = $output_message->errorOutput('No notes available');
        }
    
    
        return $api_output;
    }

    public function get_history($input_data){

        // error_reporting(E_ALL);
        // ini_set('display_errors', '1');

        $history_list = [];
        
        $notes_sql = "  SELECT a.*, IFNULL(a.updated_date, a.created_date) AS date
                        FROM " . tbl_notes . " a
                        WHERE (DATE(a.created_date) >= NOW() - INTERVAL 30 DAY) || (DATE(a.updated_date) >= NOW() - INTERVAL 30 DAY)
                        ORDER BY date DESC";
        $notes_query = mysqli_query($this->db_con, $notes_sql);
    
        while ($note = mysqli_fetch_assoc($notes_query)) {
            $updated_date = $note["updated_date"];
            $created_date = $note["created_date"];
            $note_id = $note["id"];
            $is_archived = $note["is_archived"];
            $is_deleted = $note["is_deleted"];
            $ip_address = $note["ip_address"];
            $updated_by_ip = $note["updated_by_ip"];

            if($is_deleted){
                $history_list[] = "Note has been deleted with ID #$note_id on " . date('m/d/Y', strtotime($updated_date)) . " by IP: $updated_by_ip";
            // }else if($is_archived){
            //     $history_list[] = "Archived note with ID #$note_id on " . date('m/d/Y', strtotime($updated_date)) . " by IP: $updated_by_ip";
            }else {
                $history_list[] = "Note has been created with ID #$note_id on " . date('m/d/Y', strtotime($created_date)) . " by IP: $ip_address";
            }
        }

        // echo '<pre>';
        // print_r($history_list);
        // exit;

        $output_message = new OutputMessage();

        $api_output = $output_message->successOutput(["list" => $history_list], 'Notes history loaded');
        return $api_output;
    }

    public function get_archived($input_data): array
    {
        $where = [
            "a.is_deleted = 0",
            "a.is_archived = 1",
        ];

        $result = $this->generic_list($where);
        $output_message = new OutputMessage();

        if($result && count($result) > 0){
            $api_output = $output_message->successOutput(["list" => $result], 'All archived notes loaded');
        } else {
            $api_output = $output_message->errorOutput('No archived notes available');
        }
    
        return $api_output;
    }


    private function generic_list($where){
        $result = [];
        
        $where_sql = implode(" AND ", $where);
        $notes_sql = "  SELECT a.*, IFNULL(a.updated_date, a.created_date) AS date, CONCAT(b.first_name, ' ', b.last_name) AS usr_full_name
                        FROM " . tbl_notes . " a
                        LEFT JOIN " . tbl_usr . " b ON a.usr_uid = b.uid AND b.status = 'true'
                        WHERE $where_sql 
                        ORDER BY date DESC";
        $notes_query = mysqli_query($this->db_con, $notes_sql);
       
        if (mysqli_num_rows($notes_query) > 0) {
            $notes_data = [];
    
            while ($note = mysqli_fetch_assoc($notes_query)) {
                $attachment_url = "";
                if (!empty($note['attachment'])) {
                    $attachment_url = file_via_url . "note_attachment/" . $note['attachment'];
                }
    
                $tmp_data = [
                    "id" => $note["id"],
                    "note" => $note["note"],
                    "usr_uid" => $note["usr_uid"],
                    "usr_full_name" => strtoupper($note["usr_full_name"]),
                    "ip_address" => $note["ip_address"],
                    "attachment" => $attachment_url,
                    "created_date" => date('m/d/Y', strtotime( $note["created_date"])),
                    "updated_date" => $note["updated_date"] === null || empty($note["updated_date"]) ? $note["updated_date"] : date('m/d/Y', strtotime( $note["updated_date"])),
                    "date" => date('m/d/Y', strtotime( $note["updated_date"] != null? $note["updated_date"]:$note["created_date"]))
                ];
    
                $notes_data[] = $tmp_data;
            }
             
            $result = $notes_data;
        }
        return $result;
    } 
    
    public function save($input_data)
    {
        
        // error_reporting(E_ALL);
        // ini_set('display_errors', '1');

        $item_details = new ItemDetails();
        $output_message = new OutputMessage();

        $note_id       = mysqli_real_escape_string($this->db_con, $input_data->note_id);
        $usr_auth   = mysqli_real_escape_string($this->db_con, $input_data->usr_auth);
        $usr_id     = mysqli_real_escape_string($this->db_con, $input_data->usr_id);
        $note       = mysqli_real_escape_string($this->db_con, $input_data->note);
        $ip_address = mysqli_real_escape_string($this->db_con, $input_data->ip_address);

        $attachment = isset($input_data->attachment) ? basename($input_data->attachment) : '';
        $attachment_data     = isset($input_data->attachment_data) ? $input_data->attachment_data : '';

        
        $upload_dir = file_via_loc . 'note_attachment/';
        $file_name = '';
        if (isset($attachment) && isset($attachment_data) && $attachment_data!= '') {
            // Decode base64 and save file
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            $extension = pathinfo($attachment, PATHINFO_EXTENSION);
            $file_name = time() . '.' . $extension;
            $file_path = $upload_dir . $file_name;

            $decoded_data = base64_decode($attachment_data);
            if ($decoded_data === false) {
                return $output_message->errorOutput('Failed to decode file data');
            }

            if (file_put_contents($file_path, $decoded_data) === false) {
                return $output_message->errorOutput('Failed to save file');
            }


            if($note_id > 0){
                $existing_note_sql = "SELECT attachment FROM " . tbl_notes . " WHERE id = '$note_id'";
                $exiting_note_result = mysqli_query($this->db_con, $existing_note_sql);
                $existing_note = mysqli_fetch_assoc($exiting_note_result);
                $existing_note_attachment = $existing_note['attachment'];

                if ($existing_note_attachment && file_exists($upload_dir . $existing_note_attachment)) {
                    unlink($upload_dir . $existing_note_attachment);
                }
            }
        }

        if($note_id > 0){
            
            // Update DB
            $note_sql = "
                UPDATE " . tbl_notes . "
                SET usr_uid = '$usr_id', note = '$note', updated_by_ip = '$ip_address', updated_date = NOW()
            ";

            if($file_name != ''){
                $note_sql .= " ,attachment = '$file_name' ";
            }

            $note_sql .= "  WHERE id = '$note_id' ";

        }else{
            // Insert into DB
            $note_sql = "
                INSERT INTO " . tbl_notes . " (usr_uid, note, ip_address, attachment)
                VALUES ('$usr_id', '$note', '$ip_address', '$file_name')
            ";
        }
        

        if (mysqli_query($this->db_con, $note_sql)) {
            return $output_message->successOutput([], 'Note saved successfully');
        } else {
            return $output_message->errorOutput('Failed to save note');
        }
    }

    public function delete($input_data)
    {
    
        $output_message = new OutputMessage();

        // Retrieve data from input
        $usr_auth = mysqli_real_escape_string($this->db_con, $input_data->usr_auth);
        $note_id = mysqli_real_escape_string($this->db_con, $input_data->note_id);
        $ip_address = mysqli_real_escape_string($this->db_con, $input_data->ip_address);
    

        // Delete note record from database
        $delete_sql = "UPDATE " . tbl_notes . "  set is_deleted = 1, updated_by_ip = '$ip_address',updated_date = NOW() WHERE id = '$note_id'";

        if (mysqli_query($this->db_con, $delete_sql)) {
            return $output_message->successOutput([], 'Note deleted successfully');
        } else {
            return $output_message->errorOutput('Failed to delete note');
        }
    }

    public function archive($input_data)
    {
        $output_message = new OutputMessage();
        // Retrieve data from input
        $usr_auth = mysqli_real_escape_string($this->db_con, $input_data->usr_auth);
        $note_id = mysqli_real_escape_string($this->db_con, $input_data->note_id);
        $ip_address = mysqli_real_escape_string($this->db_con, $input_data->ip_address);
        $is_archived = mysqli_real_escape_string($this->db_con, $input_data->is_archived);
    

        $update_sql = "UPDATE " . tbl_notes . "  set is_archived = $is_archived, updated_by_ip = '$ip_address',updated_date = NOW() WHERE id = '$note_id'";

        $update_text = 'archived';
        if ($is_archived == 0) {
            $update_text = 'activated';
        }


        if (mysqli_query($this->db_con, $update_sql)) {
            return $output_message->successOutput([], "Note $update_text successfully");
        } else {
            return $output_message->errorOutput("Failed to $update_text note");
        }
    }

    public function get_single($input_data): array
    {
        // error_reporting(E_ALL);
        // ini_set('display_errors', '1');

        $output_message = new OutputMessage();
        $beautify_arr = new ItemBeautify();


        $note_id = mysqli_real_escape_string($this->db_con, $input_data->note_id);

        $sql = "SELECT * FROM ". tbl_notes . " WHERE id = '$note_id'";
        $result = mysqli_query($this->db_con, $sql);
        $note = mysqli_fetch_assoc($result);

        if (isset($note)) {
            return $output_message->successOutput($note, "Note details loaded successfully");
        } else {
            return $output_message->errorOutput("Note not found or inactive");
        }
    }
}