<?php

require_once APP_ROOT . '/models/Collection.php';
require_once APP_ROOT . '/models/Subcollection.php';
require_once APP_ROOT . '/models/Item.php';
require_once APP_ROOT . '/models/User.php';
require_once APP_ROOT . '/models/Setting.php';
require_once APP_ROOT . '/helpers/Mailer.php';

class ShareController
{
    public function __construct()
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }
    }

    public function share(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/collections/' . $id);
            exit;
        }

        $collectionModel = new Collection();
        $collection = $collectionModel->findById((int)$id);

        if (!$collection || $collection['user_id'] !== Session::getUserId()) {
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        $username = trim($_POST['username'] ?? '');
        if (empty($username)) {
            Session::flash('error', Lang::get('username_required'));
            header('Location: ' . APP_URL . '/collections/' . $id);
            exit;
        }

        $userModel = new User();
        $targetUser = $userModel->findByUsername($username);

        if (!$targetUser) {
            Session::flash('error', Lang::get('user_not_found'));
            header('Location: ' . APP_URL . '/collections/' . $id);
            exit;
        }

        if ($targetUser['id'] === Session::getUserId()) {
            Session::flash('error', Lang::get('cannot_share_self'));
            header('Location: ' . APP_URL . '/collections/' . $id);
            exit;
        }

        $newId = $collectionModel->deepCopy((int)$id, $targetUser['id']);

        error_log("Share attempt: collection_id=$id, target_user={$targetUser['username']}, new_id=$newId");

        if ($newId) {
            Session::flash('success', Lang::get('collection_shared'));
        } else {
            Session::flash('error', Lang::get('error'));
        }
        header('Location: ' . APP_URL . '/collections/' . $id);
        exit;
    }

    public function cloneTemplate(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        $collectionModel = new Collection();
        $collection = $collectionModel->findById((int)$id);

        if (!$collection || !$collection['is_template']) {
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        $newId = $collectionModel->deepCopy((int)$id, Session::getUserId(), false);

        if ($newId) {
            Session::flash('success', Lang::get('template_cloned'));
        } else {
            Session::flash('error', Lang::get('error'));
        }
        header('Location: ' . APP_URL . '/home');
        exit;
    }

    public function shareEmail(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Invalid request.']);
            exit;
        }

        $collectionModel = new Collection();
        $collection = $collectionModel->findById((int)$id);

        if (!$collection || $collection['user_id'] !== Session::getUserId()) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Collection not found or access denied.']);
            exit;
        }

        $recipients = trim($_POST['recipients'] ?? '');
        $message = trim($_POST['message'] ?? '');

        if (empty($recipients)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Email recipients are required.']);
            exit;
        }

        // Parse email addresses
        $emails = array_map('trim', explode(',', $recipients));
        $emailRegex = '/^[^\s@]+@[^\s@]+\.[^\s@]+$/';
        
        $settingModel = new Setting();
        
        foreach ($emails as $email) {
            if (!preg_match($emailRegex, $email)) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => "Invalid email format: $email"]);
                exit;
            }
        }

        // Generate collection details for email
        $subModel = new Subcollection();
        $subcollections = $subModel->getAllByCollection((int)$id);
        
        $collectionDetails = "
        <h2>{$collection['name']}</h2>
        <p><strong>Type:</strong> " . ucfirst($collection['type']) . "</p>
        <p><strong>Description:</strong> {$collection['description']}</p>
        <p><strong>Subcollections:</strong> " . count($subcollections) . "</p>
        ";

        if (!empty($message)) {
            $collectionDetails .= "<p><strong>Message from sender:</strong> " . nl2br(htmlspecialchars($message)) . "</p>";
        }

        $collectionDetails .= "
        <p>This collection was shared with you from NotaphilyCatalogue application.</p>
        <p>You can view more collections at: <a href='" . APP_URL . "'>" . APP_URL . "</a></p>
        ";

        $subject = "Collection Shared: {$collection['name']} from NotaphilyCatalogue";
        
        error_log("Email share attempt: collection_id=$id, recipients=" . implode(',', $emails) . ", provider=" . ($settingModel->get('email_provider') ?? 'unknown'));
        
        $successCount = 0;
        $failureCount = 0;
        
        foreach ($emails as $email) {
            error_log("Attempting to send collection share email to: $email");
            $emailSent = Mailer::send($email, $subject, $collectionDetails);
            if ($emailSent) {
                $successCount++;
                error_log("Successfully sent collection share email to: $email");
            } else {
                $failureCount++;
                error_log("Failed to send collection share email to: $email");
            }
        }

        error_log("Email share completed: success=$successCount, failed=$failureCount");

        header('Content-Type: application/json');
        if ($failureCount === 0) {
            echo json_encode(['success' => true, 'message' => "Collection successfully shared with $successCount recipient(s)."]);
        } else {
            echo json_encode(['success' => false, 'message' => "Failed to send to $failureCount recipient(s). Successfully sent to $successCount recipient(s)."]);
        }
        exit;
    }
}
