<?php
    session_start();
	include_once("../config.php");
	include_once("../functions.php");
    if (isset($_SESSION['user_id'])) {
		$data = post_input_serilization();
        if (isset($data['token']) && $data['token'] == 'getUnoccupiedUnitInfo') {
    $html = '<option value="">--Select Unit--</option>';
    if (isset($data['bid']) && (int)$data['bid'] > 0) {
        $unit_no = '';
        // Query to group by uid
        $query = "SELECT uid, unit_no FROM unit_view WHERE bid = " . (int)$data['bid'] . " GROUP BY uid ORDER BY unit_no ASC";
        $result = $link->query($query);

        // Debug: output the SQL query
        echo $query;

        // Build the HTML options
        while ($rows = mysqli_fetch_array($result)) {
            $html .= '<option value="'. $rows['uid'] .'">'. $rows['unit_no'] . '</option>';
        }

        // Output the final HTML
        echo $html;
        die();
    }
    echo '';
    die();
}elseif (isset($data['token']) && $data['token'] == 'getUnitInfo') {
    $html = '<option value="">--Select Unit--</option>';
    if (isset($data['bid']) && (int)$data['bid'] > 0) {
        $unit_no = '';
        // Query to group by uid
        $query = "SELECT uid, unit_no FROM unit_view WHERE bid = " . (int)$data['bid'] . " GROUP BY uid ORDER BY unit_no ASC";
        $result = $link->query($query);

        // Debug: output the SQL query
        echo $query;

        // Build the HTML options
        while ($rows = mysqli_fetch_array($result)) {
            $html .= '<option value="'. $rows['uid'] .'">'. $rows['unit_no'] . '</option>';
        }

        // Output the final HTML
        echo $html;
        die();
    }
    echo '';
    die();
} elseif (isset($data['token']) && $data['token'] === 'getAvailableDatesForCurrentMonth') {
    $uid = (int)$data['uid'];

    // Get today's date and the date six months from now
    $start_date = date("Y-m-d");  
    $end_date   = date("Y-m-d", strtotime("+6 months", strtotime($start_date)));

    // Query to get all booked date ranges for the unit overlapping [today, six months ahead]
    $sql = "
        SELECT start_date, end_date
          FROM rent
         WHERE uid = '{$uid}'
           AND (
                 (start_date BETWEEN '{$start_date}' AND '{$end_date}')
              OR (end_date   BETWEEN '{$start_date}' AND '{$end_date}')
              OR (start_date <= '{$start_date}' AND end_date >= '{$end_date}')
           )
    ";
    $query = $link->query($sql);

    // Build array of every date from today through six months ahead
    $all_dates  = [];
    $current_ts = strtotime($start_date);
    $end_ts     = strtotime($end_date);
    while ($current_ts <= $end_ts) {
        $all_dates[] = date("Y-m-d", $current_ts);
        $current_ts  = strtotime("+1 day", $current_ts);
    }

    // Expand each booked range into individual dates
    $booked_dates = [];
    while ($row = mysqli_fetch_assoc($query)) {
        $s_ts = max(strtotime($row['start_date']), strtotime($start_date));
        $e_ts = min(strtotime($row['end_date']),   strtotime($end_date));
        for ($ts = $s_ts; $ts <= $e_ts; $ts = strtotime("+1 day", $ts)) {
            $booked_dates[] = date("Y-m-d", $ts);
        }
    }

    // Compute unbooked dates
    $unbooked_ts = array_diff(
        array_map('strtotime', $all_dates),
        array_map('strtotime', $booked_dates)
    );
    sort($unbooked_ts);

    // Format into human-readable ranges
    $formatted    = [];
    $range_start  = null;
    $count        = count($unbooked_ts);

    for ($i = 0; $i < $count; $i++) {
        $day  = $unbooked_ts[$i];
        $next = ($i + 1 < $count) ? $unbooked_ts[$i + 1] : null;

        if ($range_start === null) {
            $range_start = $day;
        }

        if ($next === null || $next !== strtotime('+1 day', $day)) {
            $start_label = date("jS F", $range_start);
            $end_label   = date("jS F", $day);

            if ($range_start === $day) {
                $formatted[] = $start_label;
            } else {
                $formatted[] = "{$start_label} - {$end_label}";
            }
            $range_start = null;
        }
    }

    // Prepare and send JSON response
    $response = [
        'status'          => !empty($formatted),
        'available_dates' => !empty($formatted)
            ? implode(', ', $formatted)
            : 'No available dates in the next six months'
    ];

    echo json_encode($response);
}





 elseif (isset($data['token']) && $data['token'] == 'getbookedunit') {
            $html = '<option value="">--Select Unit--</option>';
            if (isset($data['b_name']) && (int)$data['b_name'] > 0) {
                $unit_no = '';
                $result = $link->query("SELECT * FROM unit_view where b_name = '" . (int)$data['b_name'] . "' and status = 1 order by unit_no asc");
                while ($rows = mysqli_fetch_array($result)) {
                    $html .= '<option value="'.$rows['uid'].'">'.$rows['unit_no'] . '</option>';
                }
                echo $html;
                die();
            }
            echo '';
            die();
            
        } elseif (isset($data['token']) && $data['token'] == 'getbookedcediunit') {
            $html = '<option value="">--Select Unit--</option>';
            if (isset($data['b_name']) && (int)$data['b_name'] > 0) {
                $unit_no = '';
                $result = $link->query("SELECT * FROM cedi_unit_view where b_name = '" . (int)$data['b_name'] . "' and status = 1 order by unit_no asc");
                while ($rows = mysqli_fetch_array($result)) {
                    $html .= '<option value="'.$rows['uid'].'">'.$rows['unit_no'] . '</option>';
                }
                echo $html;
                die();
            }
            echo '';
            die();

        }elseif (isset($data['token']) && $data['token'] == 'getunitinforeport') {
            $html = '<option value="">--Select Unit--</option>';
            if (isset($data['bid']) && (int)$data['bid'] > 0) {
                $unit_no = '';
                $result = $link->query("SELECT * FROM unit_view where bid = '" . (int)$data['bid'] . "' order by unit_no asc");
                while ($rows = mysqli_fetch_array($result)) {
                    $html .= '<option value="'.$rows['uid'].'">'.$rows['unit_no'] . '</option>';
                }
                echo $html;
                die();
            }
            echo '';
            die();
        } elseif (isset($data['token']) && $data['token'] == 'getRentInfo') {
            $html = array(
                'tid'	=> '0',
                'name'	=> '',
                'fair'	=> '0.00'
            );
            if (isset($data['floor_id']) && (int)$data['floor_id'] > 0 && isset($data['unit_id']) && (int)$data['unit_id'] > 0) {
                $result = $link->query("SELECT * from tenants where r_floor_no = '" . (int)$data['floor_id'] . "' and r_unit_no = '" . (int)$data['unit_id'] . "' and r_status = 1");
                if ($rows = mysqli_fetch_array($result)) {
                    $html = array(
                        'tid'	=> $rows['tid'],
                        'name'	=> $rows['r_name'],
                        'fair'	=> $rows['r_rent_pm']
                    );
                }
            }
            echo json_encode($html);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'getOwnerInfo') {
            $html = array(
                'ownid'	=> '0',
                'name'	=> ''
            );
            if (isset($data['unit_id']) && (int)$data['unit_id'] > 0) {
                $result = $link->query("SELECT * from tbl_add_owner_unit_relation ur inner join tbl_add_owner ao on ao.ownid = ur.owner_id where ur.unit_id  = '" . (int)$data['unit_id'] . "'");
                if ($rows = mysqli_fetch_array($result)) {
                    $html = array(
                        'ownid'	=> $rows['owner_id'],
                        'name'	=> $rows['o_name']
                    );
                }
            }
            echo json_encode($html);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'getDesgInfo') {
            $html = '';
            if (isset($data['emp_id']) && (int)$data['emp_id'] > 0) {
                $result_emp = $link->query("SELECT *,mt.member_type from tbl_add_employee e inner join tbl_add_member_type mt on mt.member_id = e.e_designation where eid = '" . (int)$data['emp_id'] . "'");
                if ($row_emp = mysqli_fetch_array($result_emp)) {
                    $html = $row_emp['member_type'];
                }
            }
            echo $html;
            die();
        } elseif (isset($data['token']) && $data['token'] == 'getDesgInfoWithAll') {
            $output = array('data'=>'');
            if (isset($data['emp_id']) && (int)$data['emp_id'] > 0) {
                $result_emp = $link->query("SELECT *,mt.member_type from tbl_add_employee e inner join tbl_add_member_type mt on mt.member_id = e.e_designation where eid = '" . (int)$data['emp_id'] . "'");
                if ($row_emp = mysqli_fetch_array($result_emp)) {
                    $_data = array(
                        'member_type'	=> $row_emp['member_type'],
                        'salary'		=> $row_emp['salary'],
                    );
                    $output = array('data'=>$_data);
                }
            }
            echo json_encode($output);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'owner_email_exist') {
            $json = array('email_exist'=>false);
            if (isset($data['email']) && !empty($data['email'])) {
                $result_owner = $link->query("SELECT * FROM tbl_add_owner where o_email = '".trim($data['email'])."'");
                if ($row_owner = mysqli_fetch_array($result_owner)) {
                    $json = array('email_exist'=>true);
                }
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'renter_email_exist') {
            $json = array('email_exist'=>false);
            if (isset($data['email']) && !empty($data['email'])) {
                $result_renter = $link->query("SELECT * FROM tenants where r_email = '".trim($data['email'])."'");
                if ($row_renter = mysqli_fetch_array($result_renter)) {
                    $json = array('email_exist'=>true);
                }
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'tenant_email_exist') {
            $json = array('email_exist'=>false);
            if (isset($data['email']) && !empty($data['email'])) {
                $result_tenant = $link->query("SELECT * FROM tbl_tenant where email = '".trim($data['email'])."'");
                if ($row_renter = mysqli_fetch_array($result_tenant)) {
                    $json = array('email_exist'=>true);
                }
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'employee_email_exist') {
            $json = array('email_exist'=>false);
            if (isset($data['email']) && !empty($data['email'])) {
                $result_emp = $link->query("SELECT * FROM tbl_add_employee where e_email = '".trim($data['email'])."'");
                if ($row_emp = mysqli_fetch_array($result_emp)) {
                    $json = array('email_exist'=>true);
                }
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'mc_email_exist') {
            $json = array('email_exist'=>false);
            if (isset($data['email']) && !empty($data['email'])) {
                $result_emp = $link->query("SELECT * FROM tbl_add_management_committee where mc_email = '".trim($data['email'])."'");
                if ($row_emp = mysqli_fetch_array($result_emp)) {
                    $json = array('email_exist'=>true);
                }
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'updateLeaveStatus') {
            $json = array('msg'=>'');
            if (isset($data['status']) && !empty($data['leave_id'])) {
                $link->query("UPDATE tbl_employee_leave_request SET request_status = '".$data['status']."' where leave_id = ".(int)$data['leave_id']);
                $json = array('msg'=>'Updated leave status successfully');
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'updateComplainStatus') {
            $json = array('msg'=>'');
            if (isset($data['cid']) && !empty($data['cid'])) {
                $link->query("UPDATE complaints SET job_status = '".$data['status']."' where complain_id = ".(int)$data['cid']);
                $json = array('msg'=>'Updated complain status successfully');
            }
            echo json_encode($json);
            die();
        } elseif (isset($data['token']) && $data['token'] == 'updateSecurityStatus') {
            $json = array('msg' => '');
            if (isset($data['id']) && !empty($data['id'])) {
                $stmt = $link->prepare("UPDATE security_deposit SET s_status = ? WHERE id = ?");
                $stmt->bind_param("si", $data['status'], $data['id']);
                if ($stmt->execute()) {
                    $json = array('msg' => 'Updated security deposit status successfully');
                } else {
                    $json = array('msg' => 'Failed to update security deposit status');
                }
                $stmt->close();
            }
            echo json_encode($json);
            die();
        }

        elseif (isset($data['token']) && $data['token'] == 'updateTenantStatus') {
            $json = array('msg' => '');
            if (isset($data['tid']) && !empty($data['tid'])) {
                $stmt = $link->prepare("UPDATE tenants SET r_status = ? WHERE tid = ?");
                $stmt->bind_param("si", $data['status'], $data['tid']);
                if ($stmt->execute()) {
                    $json = array('msg' => 'Updated tenant status successfully');
                } else {
                    $json = array('msg' => 'Failed to update tenant status');
                }
                $stmt->close();
            }
            echo json_encode($json);
            die();
        }
        
        elseif (isset($data['token']) && $data['token'] == 'updateComplainJob') {
            if (isset($data['eid']) && !empty($data['eid'])) {
                $link->query("UPDATE complaints SET assign_employee_id = '".$data['eid']."' where complain_id = ".(int)$data['cid']);
            }
            echo 'success';
            die();
        } elseif (isset($data['token']) && $data['token'] == 'updateComplainSolution') {
            if (isset($data['cid']) && !empty($data['cid'])) {
                $link->query("UPDATE complaints SET job_status = '".$data['status']."', solution = '".$data['txt']."' where complain_id = ".(int)$data['cid']);
            }
            echo 'success';
            die();
        } elseif (isset($data['token']) && $data['token'] == 'get_tenant_unit') {
            $html = '<option value="">--Select Unit--</option>';
            if (isset($data['tid']) && (int)$data['tid'] > 0) {
                $unit_no = '';
                $result = $link->query("SELECT * from occupied_units_view where tenant_id = '" . (int)$data['tid'] . "' order by unit_no asc");
                while ($rows = mysqli_fetch_array($result)) {
                    $html .= '<option value="'.$rows['uid'].'">'.$rows['unit_no'] . '</option>';
                }
                echo $html;
                die();
            }
            echo '';
            die();
      
         
        } 
        elseif (isset($data['token']) && $data['token'] == 'getUnoccupiedSecUnit') {
            $html = '<option value="">--Select Unit--</option>';
            if(isset($data['tid']) && (int)$data['tid'] > 0) {
                $unit_no = '';
                $result = $link->query("SELECT * from rent_tenant_unit_view where tenant_id = '" . (int)$data['tid']."' order by unit_no asc");
                while($rows = mysqli_fetch_array($result)) {
                    $html .= '<option value="'.$rows['uid'].'">'.$rows['unit_no'] . '</option>';
                }
                echo $html;
                die();
            }
            echo '';
            die();
        }
        
        elseif (isset($data['token']) && $data['token'] == 'getUnitRent') {
            $html = '<option value="">--Select Unit--</option>';
            if (isset($data['uid']) && (int)$data['uid'] > 0) {
                $unit_no = '';
                $query = $link->query("SELECT rate, rate_currency, d_rate, m_rate, rate_currency_id  from unit_view where `uid` = '" . (int)$data['uid'] . "'");
                $result = mysqli_fetch_assoc($query);
                $result["rate"] = number_format($result["rate"], 2, ".", "");
                echo json_encode($result);
                die();
            } else {
                echo '';
                die();
            }
        }
        
        
        
        else if(isset($data['token']) && $data['token'] == 'getPreviousRentPeriod'){
			$query = $link->query("SELECT * FROM rent WHERE `uid` = '" . (int)$data['uid'] . "' ORDER BY end_date DESC LIMIT 1");
            $result = mysqli_fetch_assoc($query);
            $response["status"] = false;
            if(is_array($result) && count($result) >= 1){
                $response["previous"] = date("jS F, Y", strtotime($result["start_date"])) . "  -  " . date("jS F, Y", strtotime($result["end_date"]));
                $response["status"] = true;
            }
			echo json_encode($response);
		}
    } else {
        echo '-99';
        die();
    }
