<?php
/**
 * ReminderManager.php - Reminder and Follow-up Management
 * Handles reminder scheduling and automated follow-ups for unsigned documents
 */

class ReminderManager {
    private $pdo;
    private $emailHandler;

    public function __construct($pdo, $emailHandler = null) {
        $this->pdo = $pdo;
        $this->emailHandler = $emailHandler;
    }

    /**
     * Create reminder for pending documents
     */
    public function createReminder($sale_id, $document_id, $reminder_type = 'signature_pending', $reminder_text = null, $days_until = 1) {
        try {
            $scheduled_for = date('Y-m-d H:i:s', strtotime("+$days_until days"));

            $stmt = $this->pdo->prepare("
                INSERT INTO reminders (sale_id, document_id, reminder_type, reminder_text, scheduled_for)
                VALUES (:sale_id, :document_id, :reminder_type, :reminder_text, :scheduled_for)
            ");

            return $stmt->execute([
                ':sale_id' => $sale_id,
                ':document_id' => $document_id,
                ':reminder_type' => $reminder_type,
                ':reminder_text' => sanitize_input($reminder_text),
                ':scheduled_for' => $scheduled_for
            ]);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get pending reminders due now
     */
    public function getPendingReminders($limit = 50) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT r.*, s.user_id, s.customer_id, d.customer_email, d.customer_name
                FROM reminders r
                LEFT JOIN sales s ON r.sale_id = s.id
                LEFT JOIN documents d ON r.document_id = d.id
                WHERE r.status = 'pending'
                  AND r.scheduled_for <= NOW()
                  AND r.attempt_count < r.max_attempts
                ORDER BY r.scheduled_for ASC
                LIMIT :limit
            ");

            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->execute();

            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Send reminder email to customer
     */
    public function sendReminder($reminder) {
        try {
            if (!$this->emailHandler) {
                return false;
            }

            $customer_email = $reminder['customer_email'];
            $customer_name = $reminder['customer_name'];
            $reminder_type = $reminder['reminder_type'];

            // Build email content based on reminder type
            $subject = "Reminder: Signature Required";
            $body = $this->buildReminderEmail($reminder);

            if ($this->emailHandler->sendCustomEmail(
                $customer_email,
                $subject,
                $body,
                'customer'
            )) {
                // Mark reminder as sent
                $this->updateReminder($reminder['id'], 'sent');

                // Log to email_log
                $this->logReminder($reminder['sale_id'], $reminder['document_id'], $customer_email, $reminder_type);

                log_action($reminder['user_id'], $reminder['document_id'], 'REMINDER_SENT', "Reminder sent to $customer_email");

                return true;
            } else {
                // Increment attempt count
                $this->incrementAttempt($reminder['id']);
                return false;
            }
        } catch (Exception $e) {
            log_action(null, null, 'REMINDER_SEND_ERROR', 'Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Build reminder email HTML
     */
    private function buildReminderEmail($reminder) {
        $customer_name = htmlspecialchars($reminder['customer_name']);
        $reminder_text = htmlspecialchars($reminder['reminder_text'] ?? 'Complete your document signature');

        return "
        <html>
        <body style='font-family: Arial, sans-serif; color: #333;'>
            <h2>Action Required: Document Signature Needed</h2>
            <p>Hi $customer_name,</p>
            <p>We're following up on a document that still needs your signature:</p>
            <p style='background-color: #f9f9f9; padding: 15px; border-left: 4px solid #007bff;'>
                <strong>$reminder_text</strong>
            </p>
            <p>Please sign this document at your earliest convenience to complete your transaction.</p>
            <p>
                <a href='" . BASE_URL . "customer-portal.php' style='display: inline-block; background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px;'>
                    View & Sign Document
                </a>
            </p>
            <p>If you have any questions, please contact us.</p>
            <p>Thank you,<br>
            " . MAIL_FROM_NAME . "</p>
        </body>
        </html>
        ";
    }

    /**
     * Update reminder status
     */
    public function updateReminder($reminder_id, $status) {
        try {
            $stmt = $this->pdo->prepare("
                UPDATE reminders
                SET status = :status, sent_at = CURRENT_TIMESTAMP
                WHERE id = :id
            ");

            return $stmt->execute([
                ':id' => $reminder_id,
                ':status' => $status
            ]);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Increment attempt count
     */
    private function incrementAttempt($reminder_id) {
        try {
            $stmt = $this->pdo->prepare("
                UPDATE reminders
                SET attempt_count = attempt_count + 1
                WHERE id = :id
            ");

            return $stmt->execute([':id' => $reminder_id]);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Log reminder sent
     */
    private function logReminder($sale_id, $document_id, $email, $reminder_type) {
        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO email_log (sale_id, document_id, recipient_email, recipient_type, email_type, subject, status)
                VALUES (:sale_id, :document_id, :email, 'customer', 'reminder', 'Reminder: Signature Required', 'sent')
            ");

            return $stmt->execute([
                ':sale_id' => $sale_id,
                ':document_id' => $document_id,
                ':email' => $email
            ]);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Auto-create reminders for incomplete sales
     */
    public function autoCreateReminders($user_id, $hours_since_creation = 24) {
        try {
            // Get incomplete sales with unsigned documents
            $stmt = $this->pdo->prepare("
                SELECT DISTINCT s.id as sale_id, sd.document_id
                FROM sales s
                JOIN sale_documents sd ON s.id = sd.sale_id
                LEFT JOIN reminders r ON s.id = r.sale_id AND sd.document_id = r.document_id AND r.status = 'pending'
                WHERE s.user_id = :user_id
                  AND s.sale_status IN ('draft', 'pending_signatures')
                  AND sd.is_required = TRUE
                  AND sd.signed_status != 'signed'
                  AND r.id IS NULL
                  AND TIMESTAMPDIFF(HOUR, s.created_at, NOW()) >= :hours
            ");

            $stmt->execute([
                ':user_id' => $user_id,
                ':hours' => $hours_since_creation
            ]);

            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $created_count = 0;

            foreach ($results as $row) {
                if ($this->createReminder($row['sale_id'], $row['document_id'], 'signature_pending', null, 1)) {
                    $created_count++;
                }
            }

            return $created_count;
        } catch (Exception $e) {
            return 0;
        }
    }

    /**
     * Get reminders for a sale
     */
    public function getSaleReminders($sale_id) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT * FROM reminders
                WHERE sale_id = :sale_id
                ORDER BY created_at DESC
            ");

            $stmt->execute([':sale_id' => $sale_id]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Cancel reminders for a sale/document
     */
    public function cancelReminders($sale_id, $document_id = null) {
        try {
            $query = "UPDATE reminders SET status = 'cancelled' WHERE sale_id = :sale_id";
            $params = [':sale_id' => $sale_id];

            if ($document_id) {
                $query .= " AND document_id = :document_id";
                $params[':document_id'] = $document_id;
            }

            $stmt = $this->pdo->prepare($query);
            return $stmt->execute($params);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get reminder statistics
     */
    public function getStats($user_id = null) {
        try {
            $query = "
                SELECT
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                    SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
                    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled
                FROM reminders
            ";

            $params = [];

            if ($user_id) {
                $query .= " WHERE sale_id IN (SELECT id FROM sales WHERE user_id = :user_id)";
                $params[':user_id'] = $user_id;
            }

            $stmt = $this->pdo->prepare($query);
            $stmt->execute($params);

            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return null;
        }
    }
}
?>
