<?php
declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/TenantDB.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/navigation.php';

// Check permission - Labels require proposals_edit permission
requirePermission('proposals_edit');

$pdo = getPDO();

// Get current workspace company ID
$companyId = null;
$company = null;
$workspaceParam = $_GET['workspace'] ?? null;
if ($workspaceParam) {
    $stmt = $pdo->prepare('SELECT id, name, username FROM companies WHERE username = ? LIMIT 1');
    $stmt->execute([sanitizeText((string) $workspaceParam)]);
    $company = $stmt->fetch() ?: null;
    $companyId = $company['id'] ?? null;
}
if (!$companyId) {
    $companyId = TenantDB::getTenant();
    if ($companyId) {
        $stmt = $pdo->prepare('SELECT id, name, username FROM companies WHERE id = ? LIMIT 1');
        $stmt->execute([$companyId]);
        $company = $stmt->fetch() ?: $company;
    }
}

$companyDisplayName = $company['name'] ?? 'Selected workspace';
$workspaceSlug = $workspaceParam ?? ($company['username'] ?? ($companyId ? (string) $companyId : null));
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';

// Handle delete action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    $labelId = (int) ($_POST['label_id'] ?? 0);
    if ($labelId > 0 && $companyId) {
        // Fetch old label before deletion
        $stmt = $pdo->prepare("SELECT label FROM labels WHERE id = ? AND company_id = ?");
        $stmt->execute([$labelId, $companyId]);
        $oldLabelRow = $stmt->fetch();
        $oldLabelName = $oldLabelRow['label'] ?? null;
        // Delete label from proposal_labels table (only for current workspace proposals)
        $stmt = $pdo->prepare("DELETE FROM proposal_labels WHERE label = (SELECT label FROM labels WHERE id = ? AND company_id = ?) AND proposal_id IN (SELECT id FROM proposals WHERE company_id = ?)");
        $stmt->execute([$labelId, $companyId, $companyId]);
        
        // Delete from labels table
        $stmt = $pdo->prepare("DELETE FROM labels WHERE id = ? AND company_id = ?");
        $stmt->execute([$labelId, $companyId]);
        
        // Log label deletion (best-effort)
        try {
            if ($companyId) {
                $currentUser = AuthManager::getCurrentUser();
                $userId = $currentUser['id'] ?? null;
                ActivityLog::log(
                    (int) $companyId,
                    $userId ? (int) $userId : null,
                    'label_deleted',
                    'label',
                    $labelId,
                    $oldLabelName,
                    ['label' => $oldLabelName],
                    null
                );
            }
        } catch (Throwable $e) {
            // ignore logging failures
        }
        
        $workspaceParam = isset($_POST['workspace']) ? '&workspace=' . urlencode($_POST['workspace']) : (isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '');
        header('Location: /labels.php?success=deleted' . $workspaceParam);
        exit;
    }
}

// Handle rename action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'rename') {
    $labelId = (int) ($_POST['label_id'] ?? 0);
    $newName = trim($_POST['new_name'] ?? '');
    
    if ($labelId > 0 && $newName !== '' && $companyId) {
        // Get old label name
        $stmt = $pdo->prepare("SELECT label FROM labels WHERE id = ? AND company_id = ?");
        $stmt->execute([$labelId, $companyId]);
        $oldLabel = $stmt->fetch()['label'] ?? '';
        
        if ($oldLabel !== '') {
            // Update label in labels table
            $stmt = $pdo->prepare("UPDATE labels SET label = ? WHERE id = ? AND company_id = ?");
            $stmt->execute([$newName, $labelId, $companyId]);
            
            // Update all references in proposal_labels for current workspace proposals
            $stmt = $pdo->prepare("UPDATE proposal_labels SET label = ? WHERE label = ? AND proposal_id IN (SELECT id FROM proposals WHERE company_id = ?)");
            $stmt->execute([$newName, $oldLabel, $companyId]);
            
            // Log label rename (best-effort)
            try {
                if ($companyId) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyId,
                        $userId ? (int) $userId : null,
                        'label_renamed',
                        'label',
                        $labelId,
                        $newName,
                        ['label' => $oldLabel],
                        ['label' => $newName]
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
        }
        
        $workspaceParam = isset($_POST['workspace']) ? '&workspace=' . urlencode($_POST['workspace']) : (isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '');
        header('Location: /labels.php?success=renamed' . $workspaceParam);
        exit;
    }
}

// Get all labels with usage counts
try {
    // Clean up any orphaned proposal_labels first
    $pdo->exec("DELETE FROM proposal_labels WHERE proposal_id NOT IN (SELECT id FROM proposals)");
    
    $labels = $pdo->prepare(
        "SELECT l.id, l.label, COUNT(pl.proposal_id) as usage_count
         FROM labels l
         LEFT JOIN proposal_labels pl ON l.label = pl.label AND pl.proposal_id IN (SELECT id FROM proposals WHERE company_id = ?)
         WHERE l.company_id = ?
         GROUP BY l.id, l.label
         ORDER BY l.label"
    );
    $labels->execute([$companyId, $companyId]);
    $labels = $labels->fetchAll();
} catch (PDOException $e) {
    // Table doesn't exist, create it
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS labels (
            id INT PRIMARY KEY AUTO_INCREMENT,
            company_id INT NOT NULL,
            label VARCHAR(100) NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY unique_label (company_id, label)
        )
    ");
    try {
        $pdo->exec("CREATE INDEX idx_labels_company_id ON labels(company_id)");
        $pdo->exec("CREATE INDEX idx_labels_label ON labels(label)");
    } catch (PDOException $e) {
        // Index might already exist, ignore error
    }
    $labels = [];
}

$errors = [];
$successMessage = $_GET['success'] ?? null;

// Handle create new label
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $newLabel = sanitizeText($_POST['new_label'] ?? '');
    if ($newLabel !== '') {
        if (!$companyId) {
            $errors[] = 'Workspace context not available.';
        } else {
            try {
                $stmt = $pdo->prepare("INSERT IGNORE INTO labels (company_id, label) VALUES (?, ?)");
                $stmt->execute([$companyId, $newLabel]);

                // Log label creation (best-effort)
                try {
                    if ($companyId) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyId,
                            $userId ? (int) $userId : null,
                            'label_created',
                            'label',
                            null,
                            $newLabel,
                            null,
                            ['label' => $newLabel]
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }

                $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
                header('Location: /labels.php?success=created' . $workspaceParam);
                exit;
            } catch (PDOException $e) {
                $errors[] = 'Failed to create label.';
            }
        }
    } else {
        $errors[] = 'Label name is required.';
    }
}

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Labels · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<?php require_once __DIR__ . '/components/headers/page-header.php'; ?>
<body>
<?php renderNavigationNew('Labels', $currentTheme); ?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'Back to proposals',
            'url' => '/proposals.php' . $workspaceQuery,
            'type' => 'secondary',
            'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
        ],
        [
            'label' => 'Generate proposal',
            'url' => '/generate.php' . $workspaceQuery,
            'type' => 'primary',
            'icon' => 'M12 4v16m8-8H4',
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Proposals', 'url' => '/proposals.php' . $workspaceQuery, 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
        ],
        currentPage: 'Labels',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <?php
    $totalLabels = count($labels);
    $labelsInUse = 0;
    foreach ($labels as $labelRow) {
        if ((int) ($labelRow['usage_count'] ?? 0) > 0) {
            $labelsInUse++;
        }
    }
    $labelsUnused = max(0, $totalLabels - $labelsInUse);

    $successText = null;
    if ($successMessage === 'created') {
        $successText = 'Label created successfully.';
    } elseif ($successMessage === 'deleted') {
        $successText = 'Label deleted successfully.';
    } elseif ($successMessage === 'renamed') {
        $successText = 'Label renamed successfully.';
    }
    ?>

    <div class="dash-container">
        <?php if ($successText): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span><?= h($successText) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <div>
                        <?php foreach ($errors as $error): ?>
                            <p><?= h($error) ?></p>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Top Header -->
        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Proposal labels</p>
                    <h1 class="template-hero__title">Label library for <?= h($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">Keep your proposal categorization consistent. Rename labels or clean up unused ones.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $totalLabels ?> total</span>
                    <span class="status-chip"><?= $labelsInUse ?> in use</span>
                </div>
            </section>
        </div>

        <!-- Header -->
        <div class="dash-section">
            <section class="card">
                <div>
                    <p class="section-title">Snapshot</p>
                    <p class="template-section-subtitle">Quick pulse on label usage</p>
                </div>
                <div class="template-stats-grid">
                    <div class="template-stat">
                        <p class="template-stat__label">Total labels</p>
                        <p class="template-stat__value"><?= $totalLabels ?></p>
                        <p class="template-stat__hint">Across this workspace</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">In use</p>
                        <p class="template-stat__value"><?= $labelsInUse ?></p>
                        <p class="template-stat__hint">Referenced by proposals</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Unused</p>
                        <p class="template-stat__value"><?= $labelsUnused ?></p>
                        <p class="template-stat__hint">Safe to delete</p>
                    </div>
                </div>
            </section>
        </div>

        <!-- Success Messages -->
        <div class="dash-section">
            <section class="card template-builder-card">
                <div class="template-builder-form">
                    <form method="POST" class="space-y-5">
                        <input type="hidden" name="action" value="create">
                        <?php if ($workspaceSlug): ?>
                            <input type="hidden" name="workspace" value="<?= h($workspaceSlug) ?>">
                        <?php endif; ?>

                        <label class="form-field">
                            <span>New label *</span>
                            <input type="text" name="new_label" required class="field-input" placeholder="e.g. Urgent">
                        </label>

                        <div class="template-builder-actions">
                            <button type="submit" class="btn-primary">Create label</button>
                        </div>
                    </form>
                </div>
            </section>
        </div>

        <!-- Labels List -->
        <div class="dash-section">
            <section class="card">
                <div class="template-library__header">
                    <div>
                        <p class="section-title">Label library</p>
                        <p class="template-section-subtitle">Rename labels or delete unused ones</p>
                    </div>
                </div>

                <?php if ($labels): ?>
                    <div class="template-library-grid">
                        <?php foreach ($labels as $label): ?>
                            <?php
                                $labelId = (int) ($label['id'] ?? 0);
                                $labelName = (string) ($label['label'] ?? '');
                                $usageCount = (int) ($label['usage_count'] ?? 0);
                            ?>
                            <div class="template-library-card">
                                <div class="template-library-card__top">
                                    <div>
                                        <h3 class="template-library-card__title"><?= h($labelName) ?></h3>
                                        <p class="template-library-card__meta">Used in <?= $usageCount ?> proposal<?= $usageCount === 1 ? '' : 's' ?></p>
                                    </div>
                                    <span class="status-chip"><?= $usageCount > 0 ? 'In use' : 'Unused' ?></span>
                                </div>
                                <div class="template-library-card__details">
                                    <span>Label #<?= $labelId ?></span>
                                    <span><?= $usageCount > 0 ? 'Applied to proposals' : 'Safe to delete' ?></span>
                                </div>
                                <div class="template-library-card__actions">
                                    <div class="template-library-card__actions-left">
                                        <button type="button" class="btn-secondary btn-sm" onclick="showRenameForm(<?= $labelId ?>, '<?= h($labelName) ?>')">Rename</button>
                                    </div>
                                    <?php if ($usageCount === 0): ?>
                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this label?');">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="label_id" value="<?= $labelId ?>">
                                            <?php if ($workspaceSlug): ?>
                                                <input type="hidden" name="workspace" value="<?= h($workspaceSlug) ?>">
                                            <?php endif; ?>
                                            <button type="submit" class="btn-danger btn-sm">Delete</button>
                                        </form>
                                    <?php else: ?>
                                        <span class="status-chip">Locked</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <h3>No labels yet</h3>
                        <p>Create labels directly here, or add them while you generate proposals.</p>
                        <a href="/generate.php<?= $workspaceQuery ?>" class="btn-primary">Generate proposal</a>
                    </div>
                <?php endif; ?>
            </section>
        </div>
    </div>
</div>

<!-- Rename Modal -->
<div class="delete-modal-overlay" style="position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; padding: 16px;" id="renameModal">
    <div class="delete-modal-content">
        <div class="delete-modal-header">
            <p style="font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.03em; color: var(--text-tertiary); margin: 0 0 8px;">Rename</p>
            <h3 style="margin: 0; font-size: 14px; font-weight: 600; color: var(--text-primary);">Rename label</h3>
        </div>
        <form method="POST" id="renameForm" class="delete-modal-body">
            <input type="hidden" name="action" value="rename">
            <input type="hidden" name="label_id" id="renameLabelId">
            <?php if ($workspaceSlug): ?>
                <input type="hidden" name="workspace" value="<?= h($workspaceSlug) ?>">
            <?php endif; ?>

            <label class="form-field">
                <span>New label name</span>
                <input type="text" name="new_name" id="newLabelName" required class="field-input" placeholder="Enter new label name">
            </label>

            <div class="delete-modal-footer">
                <button type="button" class="btn-secondary" onclick="hideRenameForm()">Cancel</button>
                <button type="submit" class="btn-primary">Rename</button>
            </div>
        </form>
    </div>
</div>

<script>
function showRenameForm(labelId, currentName) {
    document.getElementById('renameLabelId').value = labelId;
    document.getElementById('newLabelName').value = currentName;
    document.getElementById('renameModal').style.display = 'flex';
    document.getElementById('newLabelName').focus();
}

function hideRenameForm() {
    document.getElementById('renameModal').style.display = 'none';
}

// Close modal when clicking outside
document.getElementById('renameModal').addEventListener('click', function(e) {
    if (e.target === this) {
        hideRenameForm();
    }
});
// Wire mobile menu button
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }
});
</script>

</body>
</html>
