<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');
include('header.php');

if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['phone'];

$successMsg = "";
$errorMsg   = "";

/* ================= USER DATA ================= */
$udata = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'")
);

$type = $udata['type'];

/* ================= ALLOW ONLY DISTRIBUTOR / ADMIN ================= */
if ($type != 'Distributor' && $type != 'admin') {
    die("Access Denied");
}

/* ================= ADD RETAILER ================= */
if (isset($_POST['add_retailer'])) {

    $name     = mysqli_real_escape_string($ahk_conn, trim($_POST['name']));
    $phone    = mysqli_real_escape_string($ahk_conn, trim($_POST['phone']));
    $email    = mysqli_real_escape_string($ahk_conn, trim($_POST['email']));
    $password = trim($_POST['password']);

    /* ===== VALIDATION ===== */
    if (empty($name) || empty($phone) || empty($password)) {

        $errorMsg = "All fields are required.";

    } elseif (!preg_match('/^[6-9]\d{9}$/', $phone)) {

        $errorMsg = "Invalid mobile number.";

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $errorMsg = "Invalid email address.";

    } else {

        /* ===== CHECK DUPLICATE ===== */
        $check = mysqli_query($ahk_conn,
            "SELECT id FROM users WHERE phone='$phone'"
        );

        if (mysqli_num_rows($check) > 0) {

            $errorMsg = "Mobile number already registered.";

        } else {

            /* ===== PASSWORD HASH ===== */
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            /* ===== INSERT USER ===== */
            $insert = mysqli_query($ahk_conn, "
                INSERT INTO users
                (
                    name,
                    phone,
                    email,
                    password,
                    type,
                    balance,
                    status,
                    parent
                )
                VALUES
                (
                    '$name',
                    '$phone',
                    '$email',
                    '$hashed_password',
                    'retailer',
                    '0',
                    '1',
                    '$username'
                )
            ");

            if ($insert) {
                $successMsg = "Retailer Added Successfully";
            } else {
                $errorMsg = "Database Error";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Add Retailer</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
.card-box{
    background:#fff;
    padding:25px;
    border-radius:15px;
    box-shadow:0 8px 25px rgba(0,0,0,.1);
}
</style>

</head>

<body class="bg-light">

<div class="container py-5">

<div class="row justify-content-center">
<div class="col-lg-6">

<div class="card-box">

<h3 class="mb-4 text-primary text-center">
Add Retailer
</h3>

<form method="POST">

<div class="mb-3">
<label class="fw-bold">Full Name</label>
<input type="text"
name="name"
class="form-control"
required>
</div>

<div class="mb-3">
<label class="fw-bold">Mobile Number</label>
<input type="text"
name="phone"
maxlength="10"
class="form-control"
required
oninput="this.value=this.value.replace(/\D/g,'')">
</div>

<div class="mb-3">
<label class="fw-bold">Email Address</label>
<input type="email"
name="email"
class="form-control"
required>
</div>

<div class="mb-3">
<label class="fw-bold">Password</label>
<input type="password"
name="password"
class="form-control"
required>
</div>



<button type="submit"
name="add_retailer"
class="btn btn-primary w-100">

Create Retailer

</button>

</form>

</div>

</div>
</div>

</div>

<?php if ($errorMsg): ?>
<script>
Swal.fire({
    icon: 'error',
    title: 'Failed',
    text: <?= json_encode($errorMsg) ?>
});
</script>
<?php endif; ?>

<?php if ($successMsg): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Success',
    text: <?= json_encode($successMsg) ?>
});
</script>
<?php endif; ?>

<?php include('footer.php'); ?>

</body>
</html>