<?php
declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Contract.php';
require_once __DIR__ . '/navigation.php';

// Check permission
requirePermission('contracts_view');

// Get action-specific permissions
$canCreateContract = hasPermission('contracts_create');
$canEditContract = hasPermission('contracts_edit');
$canDeleteContract = hasPermission('contracts_delete');

// Workspace context (from secure_workspace globals)
/** @var array|null $company */
/** @var int|string|null $companyId */
$workspaceParam = $_GET['workspace'] ?? null;
$companyDisplayName = $company['name'] ?? 'Workspace';
$workspaceSlug = $workspaceParam ?? ($company['username'] ?? ($companyId ?? null));
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';

// Check if this is a client trying to access contracts list
// Clients should only access signing pages, not the contracts list
if (isset($_GET['token']) && strpos($_GET['token'] ?? '', 'CLIENT_') === 0) {
    // This is a client token, redirect them away from contracts list
    http_response_code(403);
    echo '<html><head><title>Access Denied</title></head><body><h1>Access Denied</h1><p>You do not have permission to access this page.</p></body></html>';
    exit;
}

// Handle status change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'change_status') {
    $contractId = (int) ($_POST['contract_id'] ?? 0);
    $newStatus = $_POST['status'] ?? '';
    
    if ($contractId > 0 && in_array($newStatus, ['draft', 'sent', 'signed', 'completed'])) {
        $existingContract = Contract::find($contractId);
        Contract::update($contractId, ['status' => $newStatus]);

        // Log contract status change in workspace activity (best-effort)
        if ($existingContract) {
            workspace_log(
                'contract_status_changed',
                'contract',
                $contractId,
                $existingContract['title'] ?? ($existingContract['contract_number'] ?? null),
                [
                    'status' => $existingContract['status'] ?? null,
                ],
                [
                    'status' => $newStatus,
                ]
            );
        }
        header('Location: /contracts.php?success=status_changed' . $workspaceQueryAmp);
        exit;
    }
}

// Handle contract deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_contract') {
    $contractId = (int) ($_POST['contract_id'] ?? 0);
    
    if ($contractId > 0) {
        $existingContract = Contract::find($contractId);
        Contract::delete($contractId);

        // Log contract deletion in workspace activity (best-effort)
        if ($existingContract) {
            workspace_log(
                'contract_deleted',
                'contract',
                $contractId,
                $existingContract['title'] ?? ($existingContract['contract_number'] ?? null),
                null,
                null
            );
        }
        header('Location: /contracts.php?success=contract_deleted' . $workspaceQueryAmp);
        exit;
    }
}

// Handle API request for signing link
if ($_SERVER['REQUEST_METHOD'] === 'GET' && ($_GET['action'] ?? '') === 'get_signing_link') {
    $contractId = (int) ($_GET['contract_id'] ?? 0);
    
    if ($contractId > 0) {
        $contract = Contract::find($contractId);
        if ($contract) {
            // Log signing link generation in workspace activity (best-effort)
            workspace_log(
                'contract_signing_link_generated',
                'contract',
                $contractId,
                $contract['title'] ?? ($contract['contract_number'] ?? null),
                null,
                [
                    'signing_token_client' => $contract['signing_token_client'] ?? null,
                ]
            );
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'signing_link' => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]/contract_sign.php?token=" . $contract['signing_token_client'] . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '')
            ]);
            exit;
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Contract not found']);
    exit;
}

$successMessage = $_GET['success'] ?? null;
if ($successMessage === 'status_changed') {
    $successMessage = 'Contract status updated successfully.';
} elseif ($successMessage === 'contract_deleted') {
    $successMessage = 'Contract deleted successfully.';
}

$contracts = Contract::all();

// Handle client/search filter
$searchClient = $_GET['search_client'] ?? '';
if ($searchClient) {
    $contracts = array_filter($contracts, function($contract) use ($searchClient) {
        $clientName = strtolower($contract['client_name'] ?? '');
        $clientCompany = strtolower($contract['client_company'] ?? '');
        $contractTitle = strtolower($contract['title'] ?? '');
        $contractNumber = strtolower($contract['contract_number'] ?? '');
        $searchTerm = strtolower($searchClient);
        
        return strpos($clientName, $searchTerm) !== false ||
               strpos($clientCompany, $searchTerm) !== false ||
               strpos($contractTitle, $searchTerm) !== false ||
               strpos($contractNumber, $searchTerm) !== false;
    });
}

// Summary stats similar to proposals.php
 $totalContracts = count($contracts);
 $totalCompletedContracts = count(array_filter($contracts, fn($c) => ($c['status'] ?? 'draft') === 'completed'));
 $totalDraftContracts = count(array_filter($contracts, fn($c) => ($c['status'] ?? 'draft') === 'draft'));

 // 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>Contracts · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php renderNavigationNew('Contracts', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [];
    if ($canCreateContract) {
        $actions[] = ['label' => 'New contract', 'url' => '/contract_create.php', 'type' => 'primary', 'icon' => 'M12 4v16m8-8H4', 'append_workspace' => true];
    }

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2z'],
        ],
        currentPage: 'Contracts',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

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

        <?php if ($searchClient): ?>
            <div class="dash-section">
                <div class="status-banner">
                    <span>Found <?= count($contracts) ?> contract(s) matching "<?= h($searchClient) ?>"</span>
                    <a href="/contracts.php<?= $workspaceQuery ?>" class="btn-secondary btn-sm">Clear</a>
                </div>
            </div>
        <?php endif; ?>

        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Contracts</p>
                    <h1 class="template-hero__title">Contract library for <?= htmlspecialchars($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">Track drafts, send for signature, and manage client approvals in one place.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $totalContracts ?> total</span>
                    <span class="status-chip"><?= $totalCompletedContracts ?> completed</span>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-stats">
                <div class="template-stats-grid">
                    <div class="template-stat">
                        <p class="template-stat__label">Total contracts</p>
                        <p class="template-stat__value"><?= $totalContracts ?></p>
                        <p class="template-stat__hint">Across this workspace</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Completed</p>
                        <p class="template-stat__value"><?= $totalCompletedContracts ?></p>
                        <p class="template-stat__hint">Fully executed</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Drafts</p>
                        <p class="template-stat__value"><?= $totalDraftContracts ?></p>
                        <p class="template-stat__hint">Still in progress</p>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div style="margin-bottom: 16px;">
                    <p class="section-title">Filters</p>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Search contracts by client, company, title, or number</p>
                </div>
                <form method="GET" action="/contracts.php">
                    <?php if ($workspaceSlug): ?>
                        <input type="hidden" name="workspace" value="<?= h((string) $workspaceSlug) ?>">
                    <?php endif; ?>
                    <div style="display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;">
                        <div style="flex: 1; min-width: 220px;">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Search</label>
                            <div class="input-with-icon">
                                <svg style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--text-tertiary); pointer-events: none;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                                <input
                                    type="text"
                                    name="search_client"
                                    value="<?= h($searchClient) ?>"
                                    placeholder="Search contracts..."
                                    class="input"
                                    style="padding-left: 36px;"
                                >
                            </div>
                        </div>

                        <div style="display: flex; gap: 8px;">
                            <button type="submit" class="btn-primary">
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.707A1 1 0 013 7V4z"></path>
                                </svg>
                                Apply
                            </button>
                            <a href="/contracts.php<?= $workspaceQuery ?>" class="btn-secondary">
                                <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                </svg>
                                Reset
                            </a>
                        </div>
                    </div>
                </form>
            </section>
        </div>

        <div class="dash-section">
            <section class="card" style="padding: 0; overflow: hidden; margin-bottom: 0;">
                <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px;">
                    <div>
                        <p class="section-title">Contract list</p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Showing <?= count($contracts) ?> contract<?= count($contracts) === 1 ? '' : 's' ?></p>
                    </div>
                    <?php if ($canCreateContract): ?>
                        <a href="/contract_create.php<?= $workspaceQuery ?>" class="btn-secondary">New</a>
                    <?php endif; ?>
                </div>

                <?php if (empty($contracts)): ?>
                    <div class="empty-state" style="padding: 24px;">
                        <h3>No contracts yet</h3>
                        <p>Create your first contract to get started.</p>
                        <?php if ($canCreateContract): ?>
                            <a href="/contract_create.php<?= $workspaceQuery ?>" class="btn-primary">Create contract</a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div style="overflow-x: auto;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Contract</th>
                                    <th>Client</th>
                                    <th>Status</th>
                                    <th>Created</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($contracts as $contract): ?>
                                    <?php
                                    $statusLabel = ucfirst((string) ($contract['status'] ?? 'draft'));
                                    $contractNumber = $contract['contract_number'] ?? ('CTR-' . $contract['id']);
                                    $createdLabel = !empty($contract['created_at']) ? date('M j, Y', strtotime((string) $contract['created_at'])) : '';

                                    $hasPdf = !empty($contract['pdf_path']);
                                    if (!$hasPdf) {
                                        try {
                                            Contract::generatePdf((int) $contract['id']);
                                            $contract = Contract::find((int) $contract['id']);
                                            $hasPdf = !empty($contract['pdf_path']);
                                        } catch (Exception $e) {
                                            error_log('PDF generation failed for contract ' . $contract['id'] . ': ' . $e->getMessage());
                                        }
                                    }

                                    $timestamp = time();
                                    $viewLink = "/download.php?action=view&contract_id={$contract['id']}&t={$timestamp}&force=1" . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '');
                                    $editLink = "/contract_create.php?contract_id=" . (int) $contract['id'] . "&edit=1" . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '');
                                    $internalSignLink = "/contract_sign.php?token=" . h((string) ($contract['signing_token_internal'] ?? '')) . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '');
                                    ?>
                                    <tr>
                                        <td style="vertical-align: top;">
                                            <div style="display: flex; flex-direction: column; gap: 2px;">
                                                <div style="font-size: 13px; font-weight: 500; color: var(--text-primary);">
                                                    <?= h($contract['title'] ?? 'Untitled contract') ?>
                                                </div>
                                                <div style="font-size: 11px; color: var(--text-secondary);"><?= h((string) $contractNumber) ?></div>
                                            </div>
                                        </td>
                                        <td style="vertical-align: top;">
                                            <div style="font-size: 13px; color: var(--text-primary);"><?= h($contract['client_name'] ?? 'Unknown') ?></div>
                                            <?php if (!empty($contract['client_company'])): ?>
                                                <div style="font-size: 11px; color: var(--text-secondary);"><?= h($contract['client_company']) ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td style="vertical-align: top;">
                                            <span class="status-chip"><?= h($statusLabel) ?></span>
                                        </td>
                                        <td style="vertical-align: top; font-size: 11px; color: var(--text-secondary);"><?= h($createdLabel) ?></td>
                                        <td style="vertical-align: top; text-align: right;">
                                            <div style="display: flex; justify-content: flex-end; gap: 6px; flex-wrap: wrap;">
                                                <?php if ($hasPdf): ?>
                                                    <a href="<?= $viewLink ?>" target="_blank" class="btn-secondary btn-sm" style="white-space: nowrap;">View</a>
                                                <?php endif; ?>

                                                <?php if ($canEditContract): ?>
                                                    <a href="<?= $editLink ?>" class="btn-secondary btn-sm" style="white-space: nowrap;">Edit</a>
                                                <?php endif; ?>

                                                <?php if (empty($contract['client_signed_at'])): ?>
                                                    <button type="button" onclick="copySigningLink(<?= (int) $contract['id'] ?>, this)" class="btn-secondary btn-sm" style="white-space: nowrap;">Get client sign</button>
                                                <?php else: ?>
                                                    <span class="btn-secondary btn-sm" style="white-space: nowrap; cursor: default; pointer-events: none;">Client signed</span>
                                                <?php endif; ?>

                                                <?php if (empty($contract['internal_signed_at'])): ?>
                                                    <a href="<?= $internalSignLink ?>" class="btn-secondary btn-sm" style="white-space: nowrap;">Company sign</a>
                                                <?php else: ?>
                                                    <span class="btn-secondary btn-sm" style="white-space: nowrap; cursor: default; pointer-events: none;">Company signed</span>
                                                <?php endif; ?>

                                                <form method="POST" onsubmit="return confirm('Change contract status?')" style="display: inline;">
                                                    <input type="hidden" name="action" value="change_status">
                                                    <input type="hidden" name="contract_id" value="<?= (int) $contract['id'] ?>">
                                                    <select name="status" onchange="this.form.submit()" class="input" style="padding: 4px 10px; font-size: 11px; white-space: nowrap;">
                                                        <option value="draft" <?= ($contract['status'] ?? 'draft') === 'draft' ? 'selected' : '' ?>>Draft</option>
                                                        <option value="sent" <?= ($contract['status'] ?? 'draft') === 'sent' ? 'selected' : '' ?>>Sent</option>
                                                        <option value="signed" <?= ($contract['status'] ?? 'draft') === 'signed' ? 'selected' : '' ?>>Signed</option>
                                                        <option value="completed" <?= ($contract['status'] ?? 'draft') === 'completed' ? 'selected' : '' ?>>Completed</option>
                                                    </select>
                                                </form>

                                                <?php if ($canDeleteContract): ?>
                                                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete this contract? This action cannot be undone.')" style="display: inline;">
                                                        <input type="hidden" name="action" value="delete_contract">
                                                        <input type="hidden" name="contract_id" value="<?= (int) $contract['id'] ?>">
                                                        <button type="submit" class="btn-danger btn-sm" style="white-space: nowrap;">Delete</button>
                                                    </form>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
        </div>
    </div>
</div>

<script>
// Copy signing link functionality
function copySigningLink(contractId, buttonEl) {
    const ws = <?= json_encode($workspaceSlug ? (string) $workspaceSlug : null) ?>;
    const wsQuery = ws ? `&workspace=${encodeURIComponent(ws)}` : '';
    fetch(`/contracts.php?action=get_signing_link&contract_id=${contractId}${wsQuery}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                navigator.clipboard.writeText(data.signing_link).then(function() {
                    if (!buttonEl) return;
                    const originalText = buttonEl.textContent;
                    buttonEl.textContent = 'Copied!';
                    setTimeout(function() {
                        buttonEl.textContent = originalText;
                    }, 2000);
                }).catch(function(err) {
                    console.error('Failed to copy link: ', err);
                    alert('Failed to copy link. Please copy manually: ' + data.signing_link);
                });
            } else {
                alert('Error getting signing link: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to get signing link. Please try again.');
        });
}
</script>

</body>
</html>
