<?php include "header.php"; ?>
<?php
  // NOTE: header.php already opens <html><head>...<body> and includes
  // config.php ($conn). The previous version of this file printed a SECOND
  // full <!DOCTYPE html><html><head> block right here (with its own
  // SweetAlert2 script tag, a different version than the one loaded at the
  // bottom of the page) — two nested HTML documents on one page. Removed.
  if (isset($_POST['create'])) {

   $mobile =  $_POST['mobile'];
    $email = $_POST['email'];

    // Check if the mobile number already exists in the database
    $checkMobileQuery = "SELECT * FROM `users` WHERE `mobile` = '$mobile'";
    $checkMobileResult = mysqli_query($conn, $checkMobileQuery);

    // Check if the email already exists in the database
    $checkEmailQuery = "SELECT * FROM `users` WHERE `email` = '$email'";
    $checkEmailResult = mysqli_query($conn, $checkEmailQuery);

    if (mysqli_num_rows($checkMobileResult) > 0) {
        // The mobile number already exists, display an error message
        echo '
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        Swal.fire({
            title: "Opps! Your Mobile no Already Exist!",
            text: "Please Click Ok Button!!",
            confirmButtonText: "Ok",
            icon: "error",
            background: "#14141f",
            color: "#fff"
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "add_merchant";
            }
        });
    </script>
';
    exit;
    } elseif (mysqli_num_rows($checkEmailResult) > 0) {
        // The email already exists, display an error message
        echo '
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        Swal.fire({
            title: "Opps! Your Email no Already Exist!",
            text: "Please Click Ok Button!!",
            confirmButtonText: "Ok",
            icon: "error",
            background: "#14141f",
            color: "#fff"
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "add_merchant";
            }
        });
    </script>
';
    exit;
    } else {
        // Proceed with user registration
        $password =  $_POST['password'];
    $name =  $_POST['name'];
    $company =  $_POST['company'];
    $pin =  $_POST['pin'];
    $pan =  $_POST['pan'];
    $aadhaar =  $_POST['aadhaar'];
    $location =  $_POST['location'];
        $key = md5(rand(00000000, 99999999));
        $pass = password_hash($password, PASSWORD_BCRYPT);
        // BUG FIX: the previous line was `(date("Y-m-d") + 3)`, which adds 3
        // to a *string* date. PHP casts "2026-07-26" to the number 2026 for
        // that arithmetic, giving "2029" — not a real date. strtotime()
        // happens to parse a bare 4-digit string as Jan 1 of that year, so
        // every new merchant was silently getting an expiry of roughly
        // "Jan 1, 2029" instead of 3 days from signup. Fixed to actually
        // add 3 days.
        $today = date("Y-m-d", strtotime("+3 days"));

        $register = "INSERT INTO `users`(`name`, `mobile`, `role`, `password`, `email`, `company`, `pin`, `pan`, `aadhaar`, `location`, `user_token`, `expiry`) VALUES ('$name','$mobile','User','$pass','$email','$company','$pin','$pan','$aadhaar','$location','$key','$today')";
        $result = mysqli_query($conn, $register);

        $msg = "Dear $name thanks For Registering Us
        Your Username: $mobile
        Your Password: $password
        Thanks & Regards
        IMB Shop";
        $encodedMsg = urlencode($msg);

   if($result){
       //file_get_contents("https://wamsg.tk/wa.php?api_key=Wn62PIQ09X8BiY7iOtnEmgBCFFTDM3&sender=918145511275&number=91$mobile&message=$encodedMsg");
        echo '
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        Swal.fire({
            title: "Congratulations! User Added!",
            text: "Please Click Ok Button!!",
            confirmButtonText: "Ok",
            icon: "success",
            background: "#14141f",
            color: "#fff"
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "dashboard";
            }
        });
    </script>
';
    exit;
   }else{
        echo '
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        Swal.fire({
            title: "Opps! Something Went Wrong!",
            text: "Please Click Ok Button!!",
            confirmButtonText: "Ok",
            icon: "error",
            background: "#14141f",
            color: "#fff"
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "add_merchant";
            }
        });
    </script>
';
    exit;
   }
  }
  }

  if($userdata["role"] != 'Admin'){
   echo '<script>
 window.location.href = "dashboard";
</script>';

    exit;
}

  ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .am-wrap{padding:20px;max-width:820px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .am-head{margin-bottom:22px}
    .am-head h1{font-size:1.5rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .am-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .am-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
    }
    .card-body{padding:26px}

    .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    @media(max-width:600px){.form-grid{grid-template-columns:1fr}}
    .form-group{margin-bottom:18px}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:12px 14px;color:#fff;font-size:.9rem;outline:none;transition:.2s;font-family:'Inter',sans-serif;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    .form-control::placeholder{color:rgba(255,255,255,.3)}

    .pw-wrap{position:relative}
    .pw-toggle{
        position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;
        color:rgba(255,255,255,.35);cursor:pointer;font-size:.9rem;padding:4px;
    }
    .pw-toggle:hover{color:var(--p)}
    .pw-wrap .form-control{padding-right:42px}

    .note-line{font-size:.76rem;color:rgba(255,255,255,.4);margin-top:8px;display:flex;gap:6px;align-items:flex-start}
    .note-line i{margin-top:2px;flex-shrink:0;color:var(--p)}

    .btn-primary-cta{
        width:100%;background:var(--g);border:none;color:#fff;padding:13px;border-radius:10px;
        font-size:.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);margin-top:8px;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}
</style>

<div class="am-wrap">
    <div class="am-head">
        <h1><span class="icn"><i class="fas fa-user-plus"></i></span>Add Merchant</h1>
        <p>Onboard a new merchant with a 3-day trial account</p>
    </div>

    <div class="glass-card">
        <div class="card-body">
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Mobile Number</label>
                        <input type="text" name="mobile" placeholder="Enter Mobile Number" class="form-control"
                               oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <div class="pw-wrap">
                            <input type="password" name="password" id="newMerchantPw" placeholder="Enter Password" class="form-control" required>
                            <button type="button" class="pw-toggle" onclick="togglePw('newMerchantPw', this)"><i class="fas fa-eye"></i></button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Email Address</label>
                        <input type="email" name="email" placeholder="Enter Email Address" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Name</label>
                        <input type="text" name="name" placeholder="Enter Name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Company</label>
                        <input type="text" name="company" placeholder="Enter Company" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Area Pin</label>
                        <input type="text" name="pin" placeholder="Area Pin" class="form-control"
                               oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 6);" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">PAN Number</label>
                        <input type="text" name="pan" placeholder="Enter PAN Number" class="form-control" maxlength="10" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Aadhaar Number</label>
                        <input type="text" name="aadhaar" placeholder="Enter Aadhaar Number" class="form-control"
                               oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12);" required>
                    </div>
                    <div class="form-group" style="grid-column:1/-1">
                        <label class="form-label">Location</label>
                        <input type="text" name="location" placeholder="Enter Location" class="form-control" required>
                    </div>
                </div>
                <div class="note-line"><i class="fas fa-circle-info"></i> New merchants get a 3-day trial by default. Extend their access anytime from Manage Subscriptions.</div>
                <button type="submit" name="create" class="btn-primary-cta"><i class="fas fa-user-plus"></i> Add Merchant</button>
            </form>
        </div>
    </div>
</div>

<!-- Include necessary scripts -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<script src="assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
<script>
    function togglePw(id, btn) {
        var input = document.getElementById(id);
        var icon = btn.querySelector('i');
        if (input.type === 'password') {
            input.type = 'text';
            icon.className = 'fas fa-eye-slash';
        } else {
            input.type = 'password';
            icon.className = 'fas fa-eye';
        }
    }
</script>
</body>
</html>
