<?php
/**
 * sales-workflow.php - Sales Workflow Management
 * Manage vehicle sales, track documents, and monitor signatures
 */

require_once('config.php');
require_once('Sale.php');
require_once('Customer.php');
require_once('Document.php');
require_once('ReminderManager.php');

if (!is_logged_in()) {
    header('Location: ' . BASE_URL . 'login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$view = $_GET['view'] ?? 'list';
$sale_id = $_GET['id'] ?? null;

$sale = new Sale($pdo);
$customer = new Customer($pdo);
$document = new Document($pdo);
$reminderManager = new ReminderManager($pdo);

// Get sales list or specific sale
if ($view === 'detail' && $sale_id) {
    $sale_info = $sale->get($sale_id, $user_id);
    if (!$sale_info) {
        header('Location: ' . BASE_URL . 'sales-workflow.php');
        exit;
    }

    $customer_info = $customer->get($sale_info['customer_id']);
    $sale_status = $sale->getSaleStatus($sale_id);
    $reminders = $reminderManager->getSaleReminders($sale_id);
} else {
    $incomplete_sales = $sale->getIncomplete($user_id);
    $sale_stats = $sale->getStats($user_id);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $view === 'detail' ? 'Sale Details' : 'Sales Workflow'; ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            color: #333;
            margin-bottom: 10px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }

        .stat-number {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 12px;
            opacity: 0.9;
        }

        .content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .sales-table {
            width: 100%;
            border-collapse: collapse;
        }

        .sales-table th {
            background: #f9f9f9;
            padding: 12px;
            text-align: left;
            font-weight: bold;
            color: #333;
            border-bottom: 2px solid #ddd;
        }

        .sales-table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
        }

        .sales-table tr:hover {
            background: #f9f9f9;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }

        .status-badge.draft {
            background: #e3e3e3;
            color: #666;
        }

        .status-badge.pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-badge.complete {
            background: #d4edda;
            color: #155724;
        }

        .progress-container {
            width: 200px;
            margin: 0 auto;
        }

        .progress-bar {
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
            margin: 8px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .progress-text {
            font-size: 12px;
            text-align: center;
            color: #666;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .sale-detail {
            max-width: 800px;
            margin: 0 auto;
        }

        .detail-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eee;
        }

        .detail-section:last-child {
            border-bottom: none;
        }

        .section-title {
            font-size: 18px;
            color: #333;
            margin-bottom: 15px;
            font-weight: bold;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: bold;
            color: #666;
        }

        .detail-value {
            color: #333;
        }

        .document-list {
            list-style: none;
        }

        .document-item {
            padding: 12px;
            background: #f9f9f9;
            border-radius: 4px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .document-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .document-type {
            font-size: 12px;
            color: #999;
        }

        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #007bff;
            text-decoration: none;
        }

        .back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <?php if ($view === 'detail' && $sale_info): ?>
            <!-- Sale Detail View -->
            <a href="sales-workflow.php" class="back-link">← Back to Sales</a>

            <div class="header">
                <h1>Sale #<?php echo $sale_id; ?> - <?php echo htmlspecialchars($customer_info['first_name'] . ' ' . $customer_info['last_name']); ?></h1>
            </div>

            <div class="content sale-detail">
                <!-- Sale Info -->
                <div class="detail-section">
                    <div class="section-title">Vehicle Information</div>
                    <div class="detail-row">
                        <span class="detail-label">Vehicle:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($sale_info['vehicle_year'] . ' ' . $sale_info['vehicle_make'] . ' ' . $sale_info['vehicle_model']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Registration:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($sale_info['vehicle_registration']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">VIN:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($sale_info['vehicle_vin'] ?? 'N/A'); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Colour:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($sale_info['vehicle_colour'] ?? 'N/A'); ?></span>
                    </div>
                </div>

                <!-- Customer Info -->
                <div class="detail-section">
                    <div class="section-title">Customer Information</div>
                    <div class="detail-row">
                        <span class="detail-label">Name:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($customer_info['first_name'] . ' ' . $customer_info['last_name']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Email:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($customer_info['email']); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Phone:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($customer_info['phone'] ?? 'N/A'); ?></span>
                    </div>
                </div>

                <!-- Sale Status -->
                <div class="detail-section">
                    <div class="section-title">Document Status</div>
                    <div style="text-align: center; margin: 20px 0;">
                        <div class="status-badge <?php echo strtolower($sale_status['is_complete'] ? 'complete' : 'pending'); ?>">
                            <?php echo ucwords(str_replace('_', ' ', $sale_info['sale_status'])); ?>
                        </div>
                    </div>

                    <div class="progress-container">
                        <div class="progress-text"><?php echo $sale_status['signed']; ?> of <?php echo $sale_status['total_required']; ?> signed</div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: <?php echo $sale_status['completion_percentage']; ?>%;"></div>
                        </div>
                        <div class="progress-text"><?php echo $sale_status['completion_percentage']; ?>% Complete</div>
                    </div>
                </div>

                <!-- Documents -->
                <div class="detail-section">
                    <div class="section-title">Documents</div>
                    <?php if (!empty($sale_status['documents'])): ?>
                    <ul class="document-list">
                        <?php foreach ($sale_status['documents'] as $doc): ?>
                        <li class="document-item">
                            <div>
                                <div class="document-name"><?php echo htmlspecialchars($doc['document_type']); ?></div>
                                <div class="document-type">
                                    <?php if ($doc['signed_status'] === 'signed'): ?>
                                        ✓ Signed
                                    <?php else: ?>
                                        ⏳ Pending
                                    <?php endif; ?>
                                </div>
                            </div>
                            <span class="status-badge <?php echo $doc['signed_status']; ?>">
                                <?php echo ucfirst($doc['signed_status']); ?>
                            </span>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php else: ?>
                    <p style="color: #999;">No documents created yet. <a href="bulk-create-documents.php?sale_id=<?php echo $sale_id; ?>">Create documents</a></p>
                    <?php endif; ?>
                </div>

                <!-- Actions -->
                <div class="detail-section" style="border-bottom: none;">
                    <a href="bulk-create-documents.php?sale_id=<?php echo $sale_id; ?>" class="btn btn-primary">+ Create Documents</a>
                    <a href="customer-portal.php?sale_id=<?php echo $sale_id; ?>&email=<?php echo urlencode($customer_info['email']); ?>" class="btn btn-secondary">View Customer Portal</a>
                </div>
            </div>

        <?php else: ?>
            <!-- Sales List View -->
            <div class="header">
                <h1>📊 Sales Workflow Management</h1>
                <p>Track vehicle sales and document signatures</p>

                <?php if ($sale_stats): ?>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $sale_stats['total']; ?></div>
                        <div class="stat-label">Total Sales</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $sale_stats['completed']; ?></div>
                        <div class="stat-label">Completed</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $sale_stats['pending']; ?></div>
                        <div class="stat-label">Pending</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo $sale_stats['draft']; ?></div>
                        <div class="stat-label">Draft</div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="content">
                <h2 style="margin-bottom: 15px; color: #333; font-size: 18px;">Incomplete Sales</h2>

                <?php if (!empty($incomplete_sales)): ?>
                <table class="sales-table">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Vehicle</th>
                            <th>Status</th>
                            <th>Documents</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($incomplete_sales as $s): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($s['vehicle_year'] . ' ' . $s['vehicle_make']); ?><br><small><?php echo htmlspecialchars($s['vehicle_registration']); ?></small></td>
                            <td><span class="status-badge <?php echo strtolower($s['sale_status']); ?>"><?php echo ucwords(str_replace('_', ' ', $s['sale_status'])); ?></span></td>
                            <td>
                                <div class="progress-container">
                                    <div class="progress-text"><?php echo $s['signed_docs']; ?>/<?php echo $s['total_docs']; ?></div>
                                    <div class="progress-bar">
                                        <div class="progress-fill" style="width: <?php echo $s['total_docs'] > 0 ? round(($s['signed_docs'] / $s['total_docs']) * 100) : 0; ?>%;"></div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="sales-workflow.php?view=detail&id=<?php echo $s['id']; ?>" class="btn btn-primary">View</a>
                                    <a href="bulk-create-documents.php?sale_id=<?php echo $s['id']; ?>" class="btn btn-success">Documents</a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p style="color: #999; text-align: center; padding: 40px 0;">No incomplete sales. Great job! 🎉</p>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
