<?php
session_start();
require_once 'includes/auth_helpers.php';
redirect_if_not_authenticated();
redirect_if_no_permission('edit_application');

require_once 'db/config.php';

$application_id = $_GET['id'] ?? null;
if (!$application_id) {
    header('Location: index.php');
    exit();
}

$customer = null;
$contacts = [];
$addresses = [];

try {
    $pdo = db();

    // Fetch customer
    $stmt = $pdo->prepare("SELECT * FROM customer_applications WHERE id = ?");
    $stmt->execute([$application_id]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($customer) {
        // Fetch contacts
        $stmt = $pdo->prepare("SELECT * FROM customer_contacts WHERE customer_application_id = ? ORDER BY is_primary DESC, id ASC");
        $stmt->execute([$application_id]);
        $contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fetch addresses
        $stmt = $pdo->prepare("SELECT * FROM customer_addresses WHERE customer_application_id = ? ORDER BY id ASC");
        $stmt->execute([$application_id]);
        $addresses = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fetch files
        $stmt = $pdo->prepare("SELECT * FROM application_files WHERE customer_application_id = ? ORDER BY created_at DESC");
        $stmt->execute([$application_id]);
        $files = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

if (!$customer) {
    http_response_code(404);
    echo "Application not found.";
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Customer Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">Customer Master</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Dashboard</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="logout.php">Logout</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container mt-4">
        <h2>Edit Customer Application #<?php echo $customer['id']; ?></h2>
        <form action="update_application.php" method="POST" id="applicationForm" enctype="multipart/form-data">
            <input type="hidden" name="customer_id" value="<?php echo $customer['id']; ?>">

            <!-- Company Details -->
            <div class="card mb-4">
                <div class="card-header">Company Details</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="company_name" class="form-label">Company Name</label>
                            <input type="text" class="form-control" id="company_name" name="company_name" value="<?php echo htmlspecialchars($customer['company_name']); ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="company_website" class="form-label">Company Website</label>
                            <input type="url" class="form-control" id="company_website" name="company_website" value="<?php echo htmlspecialchars($customer['company_website']); ?>">
                        </div>
                    </div>
                     <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="company_phone" class="form-label">Company Phone</label>
                            <input type="tel" class="form-control" id="company_phone" name="company_phone" value="<?php echo htmlspecialchars($customer['company_phone']); ?>">
                        </div>
                         <div class="col-md-6 mb-3">
                            <label for="sales_owner" class="form-label">Sales Owner</label>
                            <input type="text" class="form-control" id="sales_owner" name="sales_owner" value="<?php echo htmlspecialchars($customer['sales_owner']); ?>" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="payment_terms" class="form-label">Payment Terms</label>
                            <input type="text" class="form-control" id="payment_terms" name="payment_terms" value="<?php echo htmlspecialchars($customer['payment_terms']); ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="tags" class="form-label">Tags</label>
                            <input type="text" class="form-control" id="tags" name="tags" value="<?php echo htmlspecialchars($customer['tags']); ?>">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="notes" class="form-label">Notes</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo htmlspecialchars($customer['notes']); ?></textarea>
                    </div>
                </div>
            </div>

            <!-- Contacts -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    Contacts
                    <button type="button" class="btn btn-sm btn-primary" id="addContact"><i class="bi bi-plus-circle"></i> Add Contact</button>
                </div>
                <div class="card-body" id="contactsContainer">
                    <?php foreach ($contacts as $index => $contact): ?>
                    <div class="contact-group border p-3 mb-3">
                        <input type="hidden" name="contact[<?php echo $index; ?>][id]" value="<?php echo $contact['id']; ?>">
                        <button type="button" class="btn-close float-end" aria-label="Close" onclick="if(confirm('Are you sure you want to delete this contact?')) { this.parentElement.remove(); }"></button>
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" name="contact[<?php echo $index; ?>][is_primary]" id="contact_<?php echo $index; ?>_is_primary" value="1" <?php echo $contact['is_primary'] ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="contact_<?php echo $index; ?>_is_primary">Primary Contact</label>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3"><input type="text" name="contact[<?php echo $index; ?>][name]" class="form-control" placeholder="Name" value="<?php echo htmlspecialchars($contact['name']); ?>" required></div>
                            <div class="col-md-4 mb-3"><input type="email" name="contact[<?php echo $index; ?>][email]" class="form-control" placeholder="Email" value="<?php echo htmlspecialchars($contact['email']); ?>" required></div>
                            <div class="col-md-4 mb-3"><input type="tel" name="contact[<?php echo $index; ?>][phone]" class="form-control" placeholder="Phone" value="<?php echo htmlspecialchars($contact['phone']); ?>"></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Addresses -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    Addresses
                    <button type="button" class="btn btn-sm btn-primary" id="addAddress"><i class="bi bi-plus-circle"></i> Add Address</button>
                </div>
                <div class="card-body" id="addressesContainer">
                    <?php foreach ($addresses as $index => $address): ?>
                    <div class="address-group border p-3 mb-3">
                         <input type="hidden" name="address[<?php echo $index; ?>][id]" value="<?php echo $address['id']; ?>">
                        <button type="button" class="btn-close float-end" aria-label="Close" onclick="if(confirm('Are you sure you want to delete this address?')) { this.parentElement.remove(); }"></button>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <select name="address[<?php echo $index; ?>][type]" class="form-select" required>
                                    <option value="BILLING" <?php echo $address['address_type'] === 'BILLING' ? 'selected' : ''; ?>>Billing</option>
                                    <option value="SHIPPING" <?php echo $address['address_type'] === 'SHIPPING' ? 'selected' : ''; ?>>Shipping</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3"><input type="text" name="address[<?php echo $index; ?>][line1]" class="form-control" placeholder="Address Line 1" value="<?php echo htmlspecialchars($address['street']); ?>" required></div>
                        <div class="mb-3"><input type="text" name="address[<?php echo $index; ?>][line2]" class="form-control" placeholder="Address Line 2" value="<?php echo htmlspecialchars($address['street2']); ?>"></div>
                        <div class="row">
                            <div class="col-md-4 mb-3"><input type="text" name="address[<?php echo $index; ?>][city]" class="form-control" placeholder="City" value="<?php echo htmlspecialchars($address['city']); ?>" required></div>
                            <div class="col-md-4 mb-3"><input type="text" name="address[<?php echo $index; ?>][state]" class="form-control" placeholder="State/Province" value="<?php echo htmlspecialchars($address['state']); ?>" required></div>
                            <div class="col-md-4 mb-3"><input type="text" name="address[<?php echo $index; ?>][postal_code]" class="form-control" placeholder="Postal Code" value="<?php echo htmlspecialchars($address['zip_code']); ?>" required></div>
                        </div>
                        <div class="mb-3"><input type="text" name="address[<?php echo $index; ?>][country]" class="form-control" placeholder="Country" value="<?php echo htmlspecialchars($address['country']); ?>" required></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- File Uploads -->
            <div class="card mb-4">
                <div class="card-header">File Uploads</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="fileUpload" class="form-label">Upload New File</label>
                        <div class="input-group">
                            <input type="file" class="form-control" id="fileUpload" name="file_upload">
                            <button class="btn btn-outline-secondary" type="submit" name="upload_file">Upload</button>
                        </div>
                    </div>
                    <hr>
                    <h5>Uploaded Files</h5>
                    <ul class="list-group">
                        <?php if (empty($files)): ?>
                            <li class="list-group-item">No files uploaded yet.</li>
                        <?php else: ?>
                            <?php foreach ($files as $file): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <a href="uploads/<?php echo $file['filepath']; ?>" target="_blank"><?php echo htmlspecialchars($file['filename']); ?></a>
                                    <a href="delete_file.php?id=<?php echo $file['id']; ?>&customer_id=<?php echo $application_id; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this file?')">Delete</a>
                                </li>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </ul>
                </div>
            </div>

            <button type="submit" name="save_changes" class="btn btn-success">Save Changes</button>
            <a href="view_application.php?id=<?php echo $customer['id']; ?>" class="btn btn-secondary">Cancel</a>
        </form>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let contactIndex = <?php echo count($contacts); ?>;
            document.getElementById('addContact').addEventListener('click', function () {
                const container = document.getElementById('contactsContainer');
                const newContact = document.createElement('div');
                newContact.className = 'contact-group border p-3 mb-3';
                newContact.innerHTML = `
                    <button type="button" class="btn-close float-end" aria-label="Close" onclick="if(confirm('Are you sure you want to delete this contact?')) { this.parentElement.remove(); }"></button>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="contact[${contactIndex}][is_primary]" id="contact_${contactIndex}_is_primary" value="1">
                        <label class="form-check-label" for="contact_${contactIndex}_is_primary">Primary Contact</label>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3"><input type="text" name="contact[${contactIndex}][name]" class="form-control" placeholder="Name" required></div>
                        <div class="col-md-4 mb-3"><input type="email" name="contact[${contactIndex}][email]" class="form-control" placeholder="Email" required></div>
                        <div class="col-md-4 mb-3"><input type="tel" name="contact[${contactIndex}][phone]" class="form-control" placeholder="Phone"></div>
                    </div>`;
                container.appendChild(newContact);
                contactIndex++;
                updateRadioListeners();
            });

            let addressIndex = <?php echo count($addresses); ?>;
            document.getElementById('addAddress').addEventListener('click', function () {
                const container = document.getElementById('addressesContainer');
                const newAddress = document.createElement('div');
                newAddress.className = 'address-group border p-3 mb-3';
                newAddress.innerHTML = `
                    <button type="button" class="btn-close float-end" aria-label="Close" onclick="if(confirm('Are you sure you want to delete this address?')) { this.parentElement.remove(); }"></button>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <select name="address[${addressIndex}][type]" class="form-select" required>
                                <option value="BILLING">Billing</option>
                                <option value="SHIPPING">Shipping</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3"><input type="text" name="address[${addressIndex}][line1]" class="form-control" placeholder="Address Line 1" required></div>
                    <div class="mb-3"><input type="text" name="address[${addressIndex}][line2]" class="form-control" placeholder="Address Line 2"></div>
                    <div class="row">
                        <div class="col-md-4 mb-3"><input type="text" name="address[${addressIndex}][city]" class="form-control" placeholder="City" required></div>
                        <div class="col-md-4 mb-3"><input type="text" name="address[${addressIndex}][state]" class="form-control" placeholder="State/Province" required></div>
                        <div class="col-md-4 mb-3"><input type="text" name="address[${addressIndex}][postal_code]" class="form-control" placeholder="Postal Code" required></div>
                    </div>
                     <div class="mb-3"><input type="text" name="address[${addressIndex}][country]" class="form-control" placeholder="Country" required></div>`;
                container.appendChild(newAddress);
                addressIndex++;
            });

            function updateRadioListeners() {
                const radios = document.querySelectorAll('input[type="radio"][name^="contact"]');
                radios.forEach(radio => {
                    radio.addEventListener('change', function() {
                        if (this.checked) {
                            radios.forEach(r => {
                                if (r !== this) r.checked = false;
                            });
                        }
                    });
                });
            }
            
            updateRadioListeners();
        });
    </script>
</body>
</html>
