<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') === 'guest') {
    header("Location: login.php");
    exit;
}
$hasCompanyWorkspace = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== '';

$workspace = $_GET['workspace'] ?? 'personal';
$scope = $_GET['scope'] ?? $workspace;

/* 🚫 BLOCK PERSONAL ACCESS */
if ($workspace !== 'company' || $scope !== 'company' || !$hasCompanyWorkspace) {
    header("Location: my_documents.php?workspace=personal&scope=personal");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$user_id = (int) ($_SESSION['user_id'] ?? 0);
$search = trim($_GET['search'] ?? '');

/*
|--------------------------------------------------------------------------
| Workspace logic
|--------------------------------------------------------------------------
| personal => only personal contracts
| company  => only shared company contracts
*/
$is_company_workspace = true;
$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int) $_SESSION['active_company_id']
    : null;



function formatDateForDisplay(?string $date): string
{
    $date = trim((string) $date);
    if ($date === '') {
        return '-';
    }

    $dt = DateTime::createFromFormat('Y-m-d', $date);
    return $dt ? $dt->format('d/m/Y') : $date;
}

function getReminderDate(?string $expireDate): ?DateTime
{
    $expireDate = trim((string) $expireDate);
    if ($expireDate === '') {
        return null;
    }

    $dt = DateTime::createFromFormat('Y-m-d', $expireDate);
    if (!$dt) {
        return null;
    }

    $dt->modify('-30 days');
    return $dt;
}

function getReminderStatus(?string $expireDate): string
{
    $reminderDate = getReminderDate($expireDate);
    if (!$reminderDate) {
        return '-';
    }

    $today = new DateTime('today');
    return ($today >= $reminderDate) ? 'Remind now' : 'Waiting';
}

function getDaysLeft(?string $expireDate): ?int
{
    $expireDate = trim((string) $expireDate);
    if ($expireDate === '') {
        return null;
    }

    $expire = DateTime::createFromFormat('Y-m-d', $expireDate);
    if (!$expire) {
        return null;
    }

    $today = new DateTime('today');
    $interval = $today->diff($expire);

    if ($expire < $today) {
        return -((int) $interval->days);
    }

    return (int) $interval->days;
}

function formatDaysLeft(?string $expireDate): string
{
    $daysLeft = getDaysLeft($expireDate);

    if ($daysLeft === null) {
        return '-';
    }
    if ($daysLeft < 0) {
        return 'Expired ' . abs($daysLeft) . ' day(s) ago';
    }
    if ($daysLeft === 0) {
        return 'Expires today';
    }

    return $daysLeft . ' day(s)';
}

function getDaysLeftClass(?string $expireDate): string
{
    $daysLeft = getDaysLeft($expireDate);

    if ($daysLeft === null) {
        return 'days-muted';
    }
    if ($daysLeft < 0) {
        return 'days-expired';
    }
    if ($daysLeft <= 30) {
        return 'days-danger';
    }
    if ($daysLeft <= 90) {
        return 'days-warning';
    }
    return 'days-safe';
}

function bindOwnership(PDOStatement $stmt, bool $is_company_workspace, ?int $active_company_id, int $user_id): void
{
    if ($is_company_workspace) {
        $stmt->bindValue(':company_id', $active_company_id, PDO::PARAM_INT);
    } else {
        $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    }
}

/*
|--------------------------------------------------------------------------
| Ownership logic by workspace
|--------------------------------------------------------------------------
*/
if ($is_company_workspace) {
    $ownershipSql = "company_id = :company_id";
} else {
    $ownershipSql = "user_id = :user_id AND company_id IS NULL";
}

if ($search !== '') {
    $stmt = $db->prepare("
        SELECT *
        FROM contracts
        WHERE {$ownershipSql}
          AND (
              customer_name LIKE :search
              OR contract_title LIKE :search
              OR contract_number LIKE :search
              OR status LIKE :search
              OR original_file_name LIKE :search
              OR note LIKE :search
          )
        ORDER BY id DESC
    ");

    $like = "%{$search}%";
    bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
    $stmt->bindValue(':search', $like, PDO::PARAM_STR);
} else {
    $stmt = $db->prepare("
        SELECT *
        FROM contracts
        WHERE {$ownershipSql}
        ORDER BY id DESC
    ");

    bindOwnership($stmt, $is_company_workspace, $active_company_id, $user_id);
}

$stmt->execute();
$contracts = $stmt->fetchAll(PDO::FETCH_ASSOC);

usort($contracts, function ($a, $b) {
    $statusA = getReminderStatus($a['expire_date'] ?? '');
    $statusB = getReminderStatus($b['expire_date'] ?? '');

    $priority = [
        'Remind now' => 0,
        'Waiting' => 1,
        '-' => 2
    ];

    $rankA = $priority[$statusA] ?? 99;
    $rankB = $priority[$statusB] ?? 99;

    if ($rankA !== $rankB) {
        return $rankA <=> $rankB;
    }

    return strcmp($a['expire_date'] ?? '', $b['expire_date'] ?? '');
});

$remindNowCount = 0;
foreach ($contracts as $contract) {
    if (getReminderStatus($contract['expire_date'] ?? '') === 'Remind now') {
        $remindNowCount++;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contracts</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <style>
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 8px;
        }

        .workspace-badge {
            display: inline-flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            background: #eff8ff;
            color: #175cd3;
            border: 1px solid #b2ddff;
            margin-top: 12px;
        }

        .table-wrap {
            width: 100%;
            overflow-x: auto;
        }

        .admin-table {
            width: 100%;
            min-width: 1100px;
        }

        .action-group {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }

        @media (max-width: 768px) {
            .action-group {
                flex-direction: column;
            }

            .action-group .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
<div class="layout">

    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Contracts</h1>
                    <p>Manage customer contracts and expiry reminders.</p>
                    <div class="workspace-badge">
                        Viewing: <?php echo $is_company_workspace ? 'Company Workspace' : 'Personal Workspace'; ?>
                    </div>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <div class="card">
            <form method="GET" class="menu">
                <input
                    type="text"
                    name="search"
                    placeholder="Search contract..."
                    value="<?php echo htmlspecialchars($search); ?>"
                    style="flex:1; padding:10px; border-radius:10px; border:1px solid #ccc;"
                >
                <button class="btn btn-primary" type="submit">Search</button>
                <a href="contracts.php" class="btn btn-secondary">Clear</a>
            </form>
        </div>

        <?php if ($remindNowCount > 0): ?>
            <div class="card" style="background:#fff1f1;color:#b42318;">
                ⚠️ <strong><?php echo $remindNowCount; ?></strong> contract(s) need renewal now.
            </div>
        <?php endif; ?>

        <div class="card">
            <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:8px;">
                <div>
                    <div class="section-title">Contract List</div>
                    <div class="section-subtext">
                        Total: <strong><?php echo count($contracts); ?></strong> contract(s)
                        <?php echo $is_company_workspace ? 'in company workspace' : 'in personal workspace'; ?>
                    </div>
                </div>

                <a href="upload_contract.php" class="btn btn-primary">+ Upload Contract</a>
            </div>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Customer</th>
                            <th>Contract</th>
                            <th>Number</th>
                            <th>Start Date</th>
                            <th>Expire Date</th>
                            <th>Days</th>
                            <th>Status</th>
                            <th>Reminder</th>
                            <th>File</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!empty($contracts)): ?>
                        <?php foreach ($contracts as $row): ?>
                            <?php $reminder = getReminderStatus($row['expire_date'] ?? ''); ?>
                            <tr class="row-<?php echo htmlspecialchars(getDaysLeftClass($row['expire_date'] ?? '')); ?>">
                                <td><span class="chip"><?php echo str_pad((int)$row['id'], 4, '0', STR_PAD_LEFT); ?></span></td>
                                <td><?php echo htmlspecialchars($row['customer_name'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($row['contract_title'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($row['contract_number'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars(formatDateForDisplay($row['start_date'] ?? '')); ?></td>
                                <td><?php echo htmlspecialchars(formatDateForDisplay($row['expire_date'] ?? '')); ?></td>
                                <td>
                                    <span class="days-badge <?php echo htmlspecialchars(getDaysLeftClass($row['expire_date'] ?? '')); ?>">
                                        <?php echo htmlspecialchars(formatDaysLeft($row['expire_date'] ?? '')); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge info">
                                        <?php echo htmlspecialchars($row['status'] ?? 'Active Customer'); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($reminder === 'Remind now'): ?>
                                        <span class="badge danger">Remind now</span>
                                    <?php elseif ($reminder === 'Waiting'): ?>
                                        <span class="badge info">Waiting</span>
                                    <?php else: ?>
                                        <span class="muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($row['file_path'])): ?>
                                        <a class="link-btn" href="<?php echo htmlspecialchars($row['file_path']); ?>" target="_blank">View</a>
                                    <?php else: ?>
                                        <span class="muted">No file</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-group">
                                        <a class="btn btn-secondary btn-sm" href="edit_contract.php?id=<?php echo (int)$row['id']; ?>">Edit</a>
                                        <a class="btn btn-danger btn-sm" href="delete_contract.php?id=<?php echo (int)$row['id']; ?>" onclick="return confirm('Delete this contract?');">Delete</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="11">
                                <div class="empty-state">No contracts found.</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>
</body>
</html>