<?php
namespace App\Repositories;

use App\Database\Connection;
use App\Utils\Logger;
use PDO;
use PDOException;

class ActivityReminderRepository
{
    private $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function create($activityId, $reminderTime, $offsetMinutes = null)
    {
        try {
            $pdo = $this->db->getPdo();
            $sql = "INSERT INTO activity_reminders 
                    (activity_didar_id, reminder_time, reminder_offset_minutes, reminder_sent, created_at)
                    VALUES (?, ?, ?, 0, NOW())";
            
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([$activityId, $reminderTime, $offsetMinutes]);
            
            if ($result) {
                $insertId = $pdo->lastInsertId();
                Logger::logInfo("Activity reminder created in database", [
                    'reminder_id' => $insertId,
                    'activity_id' => $activityId,
                    'reminder_time' => $reminderTime,
                    'offset_minutes' => $offsetMinutes
                ]);
                return $insertId;
            } else {
                Logger::logError("Failed to create activity reminder in database", null, [
                    'activity_id' => $activityId,
                    'reminder_time' => $reminderTime,
                    'offset_minutes' => $offsetMinutes,
                    'error_info' => $stmt->errorInfo()
                ]);
                return false;
            }
        } catch (PDOException $e) {
            Logger::logError("Exception while creating activity reminder", $e, [
                'activity_id' => $activityId,
                'reminder_time' => $reminderTime,
                'offset_minutes' => $offsetMinutes
            ]);
            return false;
        }
    }

    public function findDueReminders()
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare("
            SELECT ar.*, a.owner_didar_id, a.title, a.due_date, a.contact_didar_id
            FROM activity_reminders ar
            JOIN activities a ON a.didar_activity_id = ar.activity_didar_id
            WHERE ar.reminder_time <= NOW() 
            AND ar.reminder_sent = 0
            AND a.is_done = 0
            ORDER BY ar.reminder_time ASC
        ");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function markAsSent($id)
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare("
            UPDATE activity_reminders 
            SET reminder_sent = 1 
            WHERE id = ?
        ");
        return $stmt->execute([$id]);
    }

    public function deleteByActivityId($activityId)
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare("
            DELETE FROM activity_reminders 
            WHERE activity_didar_id = ?
        ");
        return $stmt->execute([$activityId]);
    }

    /**
     * Get all active reminders with optional user filter
     */
    public function getAllReminders($userId = null, $isAdmin = false)
    {
        $pdo = $this->db->getPdo();
        $sql = "
            SELECT ar.*, a.title as activity_title, a.due_date, a.contact_didar_id,
                   p.id as local_person_id, p.first_name, p.last_name, u.display_name as owner_name
            FROM activity_reminders ar
            JOIN activities a ON a.didar_activity_id = ar.activity_didar_id
            LEFT JOIN persons p ON p.didar_contact_id = a.contact_didar_id
            LEFT JOIN users u ON u.didar_user_id = a.owner_didar_id
            WHERE a.is_done = 0 "; // Only active activities

        $params = [];
        if (!$isAdmin && $userId) {
            $sql .= " AND a.owner_didar_id = ? ";
            $params[] = $userId;
        }

        $sql .= " ORDER BY ar.reminder_time ASC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

