<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class NotificationController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','property_manager']);
    }

    public function index(): void
    {
        $notifications = $this->db->fetchAll(
            "SELECT n.*, CONCAT(u.first_name,' ',u.last_name) AS user_name,
                    CONCAT(t.first_name,' ',t.last_name) AS tenant_name
             FROM notifications n
             LEFT JOIN users u ON u.id=n.user_id
             LEFT JOIN tenants t ON t.id=n.tenant_id
             ORDER BY n.created_at DESC LIMIT 100"
        );
        $tenants = $this->db->fetchAll("SELECT id, CONCAT(first_name,' ',last_name) AS name, phone, email FROM tenants WHERE status='active' ORDER BY first_name");
        $this->adminView('notification.index', compact('notifications','tenants') + ['title'=>'Notifications']);
    }

    public function send(): void
    {
        $this->verifyCsrf();
        $type    = $this->input('type','sms');
        $subject = Helper::sanitize($this->input('subject',''));
        $message = $this->input('message','');
        $target  = $this->input('target','all');

        $tenants = [];
        if ($target === 'all') {
            $tenants = $this->db->fetchAll("SELECT id, phone, email, CONCAT(first_name,' ',last_name) AS name FROM tenants WHERE status='active'");
        } elseif ($target === 'select') {
            $ids = $_POST['tenant_ids'] ?? [];
            if ($ids) {
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $tenants = $this->db->fetchAll("SELECT id, phone, email, CONCAT(first_name,' ',last_name) AS name FROM tenants WHERE id IN ($placeholders)", $ids);
            }
        }

        $sent = 0;
        foreach ($tenants as $t) {
            $this->db->insert('notifications', [
                'tenant_id'   => $t['id'],
                'type'        => $type,
                'subject'     => $subject,
                'message'     => $message,
                'status'      => 'pending',
                'created_at'  => date('Y-m-d H:i:s'),
            ]);
            $sent++;
        }

        Helper::setFlash('success', "$sent notification(s) queued for sending.");
        $this->redirect(APP_URL . '/admin/notifications');
    }
}
