<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("definitions.php");

// Create connection
$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get store key from session
$storeKey = isset($_SESSION['storekey']) ? intval($_SESSION['storekey']) : 0;
if ($storeKey === 0) {
    echo 'No Store Key';
    exit;
}

$customerKey = isset($_GET['customer_key']) ? intval($_GET['customer_key']) : 0;
if ($customerKey <= 0) {
    echo 'Invalid customer key.';
    exit;
}

$isEdit = false;
$customerData = null;

// Fetch customer data and primary email if exists, only if customer belongs to store
$sql = "SELECT c.firstname, c.lastname, c.alias, ce.email
        FROM customers c
        INNER JOIN customer_mailboxes cm ON cm.customer_key = c.customer_key
        INNER JOIN mailboxes m ON m.mailbox_key = cm.mailbox_key
        LEFT JOIN customer_email ce ON ce.customer_key = c.customer_key AND ce.primary = 1
        WHERE c.customer_key = ? AND m.store_key = ?
        LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $customerKey, $storeKey);
$stmt->execute();
$result = $stmt->get_result();
$customerData = $result->fetch_assoc();
$stmt->close();

if (!$customerData) {
    echo "Customer not found or you don't have permission to edit.";
    exit;
} else {
    $isEdit = true;
}

$conn->close();
?>

<form id="customerEditForm">
    <h5><?= $isEdit ? 'Edit Customer' : 'Add New Customer' ?></h5>

    <input type="hidden" name="customer_key" value="<?= $customerKey ?>">

    <div class="mb-3">
        <label for="firstname" class="form-label">First Name <span class="text-danger">*</span></label>
        <input type="text" class="form-control" id="firstname" name="firstname" required
               value="<?= htmlspecialchars($customerData['firstname']) ?>">
    </div>

    <div class="mb-3">
        <label for="lastname" class="form-label">Last Name <span class="text-danger">*</span></label>
        <input type="text" class="form-control" id="lastname" name="lastname" required
               value="<?= htmlspecialchars($customerData['lastname']) ?>">
    </div>

    <div class="mb-3">
        <label for="alias" class="form-label">Alias</label>
        <input type="text" class="form-control" id="alias" name="alias"
               value="<?= htmlspecialchars($customerData['alias']) ?>">
    </div>

    <div class="mb-3">
        <label for="email" class="form-label">Primary Email</label>
        <input type="email" class="form-control" id="email" name="email"
               value="<?= htmlspecialchars($customerData['email'] ?? '') ?>">
    </div>

</form>