<?php
/**
 * bulk-create-documents.php - Bulk Document Creation
 * Create multiple documents for a single sale in one workflow
 */

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

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

$user_id = $_SESSION['user_id'];
$sale_id = $_GET['sale_id'] ?? null;
$step = $_POST['step'] ?? 1;
$message = '';
$error = '';

$sale = new Sale($pdo);
$document = new Document($pdo);
$customer = new Customer($pdo);
$emailHandler = new EmailHandler($pdo);

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

// Get customer info
$customer_info = $customer->get($sale_info['customer_id']);

// Get mandatory templates for this sale type
try {
    $stmt = $pdo->prepare("
        SELECT dt.* FROM signature_requirements sr
        JOIN document_templates dt ON sr.document_type = dt.document_type
        WHERE sr.user_id = :user_id AND sr.sale_type = :sale_type AND sr.is_mandatory = TRUE
        ORDER BY sr.sequence_number
    ");
    $stmt->execute([
        ':user_id' => $user_id,
        ':sale_type' => $sale_info['sale_type']
    ]);
    $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $templates = [];
}

// Process document creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step == 2) {
    $created_count = 0;
    $errors = [];

    foreach ($templates as $template) {
        try {
            $doc_id = $document->create(
                $user_id,
                $template['id'],
                $template['document_type'],
                $customer_info['first_name'] . ' ' . $customer_info['last_name'],
                $customer_info['email'],
                $customer_info['phone'],
                $sale_info['vehicle_registration'],
                $template['template_content']
            );

            if ($doc_id) {
                // Add to sale
                $sale->addDocument($sale_id, $doc_id, $template['document_type']);
                $created_count++;

                // Send signing request email
                $emailHandler->sendSigningRequest($doc_id, $customer_info['email']);
            } else {
                $errors[] = "Failed to create: " . $template['template_name'];
            }
        } catch (Exception $e) {
            $errors[] = "Error creating " . $template['template_name'];
        }
    }

    // Update sale status
    if ($created_count > 0) {
        $sale->updateStatus($sale_id, 'pending_signatures');
        $message = "$created_count documents created and sent to customer";
    }

    if (!empty($errors)) {
        $error = implode(', ', $errors);
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Documents for Sale</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: #333;
            color: white;
            padding: 20px;
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 10px;
        }

        .content {
            padding: 30px;
        }

        .sale-summary {
            background: #f9f9f9;
            padding: 15px;
            border-left: 4px solid #007bff;
            margin-bottom: 30px;
            border-radius: 4px;
        }

        .sale-summary h3 {
            color: #007bff;
            margin-bottom: 10px;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }

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

        .template-list {
            margin: 30px 0;
        }

        .template-item {
            background: #f9f9f9;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .template-item input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .template-info {
            flex: 1;
        }

        .template-name {
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .template-type {
            font-size: 12px;
            color: #999;
            text-transform: uppercase;
        }

        .mandatory-badge {
            display: inline-block;
            background: #ff6b6b;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: bold;
        }

        .message {
            padding: 12px 16px;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 30px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            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-secondary {
            background: #6c757d;
            color: white;
        }

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

        .completion {
            text-align: center;
            padding: 40px 20px;
        }

        .completion h2 {
            color: #28a745;
            margin-bottom: 20px;
            font-size: 28px;
        }

        .completion p {
            color: #666;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📄 Create Documents for Sale</h1>
        </div>

        <div class="content">
            <?php if ($message): ?>
            <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>

            <?php if ($error): ?>
            <div class="message error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <!-- Sale Summary -->
            <div class="sale-summary">
                <h3>Sale Details</h3>
                <div class="summary-row">
                    <span>Customer:</span>
                    <strong><?php echo htmlspecialchars($customer_info['first_name'] . ' ' . $customer_info['last_name']); ?></strong>
                </div>
                <div class="summary-row">
                    <span>Vehicle:</span>
                    <strong><?php echo htmlspecialchars($sale_info['vehicle_year'] . ' ' . $sale_info['vehicle_make'] . ' ' . $sale_info['vehicle_model']); ?></strong>
                </div>
                <div class="summary-row">
                    <span>Registration:</span>
                    <strong><?php echo htmlspecialchars($sale_info['vehicle_registration']); ?></strong>
                </div>
                <div class="summary-row">
                    <span>Sale Type:</span>
                    <strong><?php echo ucwords(str_replace('_', ' ', $sale_info['sale_type'])); ?></strong>
                </div>
                <div class="summary-row">
                    <span>Email:</span>
                    <strong><?php echo htmlspecialchars($customer_info['email']); ?></strong>
                </div>
            </div>

            <!-- Template Selection -->
            <h2 style="margin-bottom: 15px; color: #333; font-size: 18px;">Select Documents to Create</h2>

            <?php if (count($templates) > 0): ?>
            <form method="POST">
                <input type="hidden" name="step" value="2">

                <div class="template-list">
                    <?php foreach ($templates as $template): ?>
                    <div class="template-item">
                        <input type="checkbox" name="templates[]" value="<?php echo $template['id']; ?>" checked>
                        <div class="template-info">
                            <div class="template-name"><?php echo htmlspecialchars($template['template_name']); ?></div>
                            <div class="template-type"><?php echo ucwords(str_replace('_', ' ', $template['document_type'])); ?></div>
                        </div>
                        <span class="mandatory-badge">Required</span>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="actions">
                    <a href="sales-workflow.php?id=<?php echo $sale_id; ?>" class="btn btn-secondary">Cancel</a>
                    <button type="submit" class="btn btn-primary">Create & Send Documents</button>
                </div>
            </form>
            <?php else: ?>
            <p style="color: #999;">No mandatory document templates found for this sale type. Configure templates in settings.</p>
            <div class="actions">
                <a href="sales-workflow.php?id=<?php echo $sale_id; ?>" class="btn btn-secondary">Back</a>
            </div>
            <?php endif; ?>

            <?php if ($message && !$error): ?>
            <div class="completion">
                <h2>✓ Documents Created</h2>
                <p>All documents have been created and emailed to the customer.</p>
                <p>Customer will receive signing requests at: <strong><?php echo htmlspecialchars($customer_info['email']); ?></strong></p>
                <a href="sales-workflow.php?id=<?php echo $sale_id; ?>" class="btn btn-primary" style="margin-top: 20px;">View Sale Status</a>
            </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
