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

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "admin") {
    header("Location: ../auth/login.php");
    exit;
}

$error = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $full_name = trim($_POST["full_name"]);
    $phone = trim($_POST["phone"]);
    $email = trim($_POST["email"]);
    $password = $_POST["password"];

    if ($full_name === "" || $phone === "" || $email === "" || $password === "") {
        $error = "Full Name, Phone Number, Email and Password are required.";
    } elseif (!preg_match('/^[0-9]{8,15}$/', $phone)) {
        $error = "Please enter a valid phone number. Use numbers only, 8 to 15 digits.";
    } else {
        $checkEmail = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
        $checkEmail->execute([$email]);

        $checkPhone = $pdo->prepare("SELECT id FROM customers WHERE phone = ? LIMIT 1");
        $checkPhone->execute([$phone]);

        if ($checkEmail->fetch()) {
            $error = "Email already exists.";
        } elseif ($checkPhone->fetch()) {
            $error = "Phone number already exists.";
        } else {
            try {
                $pdo->beginTransaction();

                $hash = password_hash($password, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO users (name, phone, email, password, role, status)
                    VALUES (?, ?, ?, ?, 'customer', 'active')
                ");
                $stmt->execute([$full_name, $phone, $email, $hash]);

                $user_id = $pdo->lastInsertId();
                $customer_code = "CUS" . str_pad($user_id, 6, "0", STR_PAD_LEFT);
                $pay_id = generate_unique_pay_id($pdo);

                $stmt = $pdo->prepare("
                    INSERT INTO customers
                    (user_id, customer_code, pay_id, full_name, phone, email, balance, status)
                    VALUES (?, ?, ?, ?, ?, ?, 0, 'active')
                ");
                $stmt->execute([
                    $user_id,
                    $customer_code,
                    $pay_id,
                    $full_name,
                    $phone,
                    $email
                ]);

                $pdo->commit();

                $success = "Customer created successfully. Customer Code: " . $customer_code . " | Pay ID: " . $pay_id;
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Error: " . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Create Customer</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 30px;
        }

        .container {
            max-width: 720px;
            margin: auto;
        }

        .card {
            background: #ffffff;
            border-radius: 14px;
            padding: 28px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.08);
        }

        h1 {
            margin-top: 0;
            color: #111827;
        }

        .subtitle {
            color: #6b7280;
            margin-bottom: 22px;
        }

        label {
            font-weight: bold;
            color: #374151;
            display: block;
            margin-bottom: 6px;
        }

        input {
            width: 100%;
            padding: 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 15px;
            box-sizing: border-box;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .btn {
            padding: 11px 16px;
            border-radius: 8px;
            border: none;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            cursor: pointer;
        }

        .btn-primary {
            background: #2563eb;
            color: white;
        }

        .btn-gray {
            background: #6b7280;
            color: white;
        }

        .success {
            color: #15803d;
            background: #dcfce7;
            padding: 12px;
            border-radius: 8px;
        }

        .error {
            color: #b91c1c;
            background: #fee2e2;
            padding: 12px;
            border-radius: 8px;
        }

        .actions {
            display: flex;
            gap: 10px;
            margin-top: 22px;
        }

        .info-box {
            background: #eff6ff;
            padding: 14px;
            border-radius: 10px;
            margin-bottom: 22px;
            color: #1e3a8a;
        }

        .required {
            color: #dc2626;
        }

        .hint {
            font-size: 13px;
            color: #6b7280;
            margin-top: 6px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="card">
        <h1>Create Customer</h1>
        <p class="subtitle">Create a customer login account and wallet.</p>

        <div class="info-box">
            Customer code will be generated automatically after creation.
        </div>

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

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

        <form method="POST">
            <div class="form-group">
                <label>Full Name <span class="required">*</span></label>
                <input type="text" name="full_name" required>
            </div>

            <div class="form-group">
                <label>Phone Number <span class="required">*</span></label>
                <input type="text" name="phone" required>
                <div class="hint">Numbers only, 8 to 15 digits.</div>
            </div>

            <div class="form-group">
                <label>Email / Login Email <span class="required">*</span></label>
                <input type="email" name="email" required>
            </div>

            <div class="form-group">
                <label>Password <span class="required">*</span></label>
                <input type="password" name="password" required>
            </div>

            <div class="actions">
                <button class="btn btn-primary" type="submit">Create Customer</button>
                <a class="btn btn-gray" href="customers.php">Back to Customers</a>
            </div>
        </form>
    </div>
</div>

<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>