<?php
session_start();

include("../config/theconfig.php");

include("header.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit(); // Always exit after a header redirect
}

$logmsg = "";
if (isset($_POST["button"])) {
    // Check if login ID already exists using a prepared statement
    $stmt_check = mysqli_prepare($conn, "SELECT loginid FROM customers WHERE loginid = ?");
    mysqli_stmt_bind_param($stmt_check, "s", $_POST['loginid']);
    mysqli_stmt_execute($stmt_check);
    mysqli_stmt_store_result($stmt_check);

    if (mysqli_stmt_num_rows($stmt_check) > 0) {
        $logmsg = "<script>swal('Error!', 'LOGIN ID ALREADY EXISTS!', 'error')</script>";
    } else {
        // Hashing passwords for security
        $hashed_acc_password = password_hash($_POST['accountpassword'], PASSWORD_DEFAULT);
        $hashed_trans_password = password_hash($_POST['transactionpassword'], PASSWORD_DEFAULT);

        // Use a prepared statement for the main customer insert query
        $sql_customer = "INSERT INTO customers (
            accountno, cot, imf, phone, email, acctype, ifsccode, firstname, lastname,
            loginid, accpassword, transpassword, accstatus, country, state, city, 
            accopendate, dob, gender, activationcode, taxcode, card_long_digit, valid_thru, otp, otp_generated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

        $stmt_customer = mysqli_prepare($conn, $sql_customer);
        mysqli_stmt_bind_param(
            $stmt_customer, "ssssssssssssssssssssssss",
            $_POST['acc'], $_POST['cot'], $_POST['imf'], $_POST['phone'], $_POST['email'],
            $_POST['acctype'], $_POST['brname'], $_POST['firstname'], $_POST['lastname'],
            $_POST['loginid'], $hashed_acc_password, $hashed_trans_password,
            $_POST['accstatus'], $_POST['country'], $_POST['state'], $_POST['city'],
            $_POST['accopendate'], $_POST['dob'], $_POST['gender'], $_POST['activationcode'],
            $_POST['taxcode'], $_POST['card_long_digit'], $_POST['valid_thru'], $_POST['otp']
        );

        if (mysqli_stmt_execute($stmt_customer)) {
            // Get the new customer's ID
            $cusid = mysqli_insert_id($conn);

            // Use a prepared statement for the accounts insert query
            $sql_accounts = "INSERT INTO accounts (accno, customerid, accstatus, accopendate, accounttype, accountbalance) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt_accounts = mysqli_prepare($conn, $sql_accounts);
            mysqli_stmt_bind_param(
                $stmt_accounts, "sissss",
                $_POST['acc'], $cusid, $_POST['accstatus'], $_POST['accopendate'],
                $_POST['acctype'], $_POST['balance']
            );
            
            if (!mysqli_stmt_execute($stmt_accounts)) {
                die('Error: ' . mysqli_error($conn));
            }
            
            $logmsg = "<script>swal('Successful!', 'Your account has been created! Your Account Number is " . htmlspecialchars($_POST['acc']) . " Thank you for joining us!', 'success')</script>";
        } else {
            die('Error: ' . mysqli_error($conn));
        }

        mysqli_stmt_close($stmt_customer);
        if (isset($stmt_accounts)) {
            mysqli_stmt_close($stmt_accounts);
        }
    }
    mysqli_stmt_close($stmt_check);
}

// Fetch branch and account data
$resq = mysqli_query($conn, "SELECT * FROM branch");
$re = mysqli_query($conn, "SELECT * FROM accountmaster");

?>
<div class="dt-content-wrapper">
    <div class="dt-content">
        <div class="dt-page__header">
            <h1 class="dt-page__title">New Customer</h1>
        </div>
        <div class="col-xl-12 col-md-6 order-xl-4">
            <div class="dt-card bg-prima text-black">
                <div class="dt-card__header">
                    <div class="dt-card__heading">
                        <div class="d-flex align-items-center">
                            <i class="icon icon-users icon-fw icon-2x text-black mr-2"></i>
                            <h3 class="dt-card__title text-black">Create New Customer</h3>
                        </div>
                    </div>
                    </div>
                <script language="javascript">
                    // NOTE: This JavaScript function is incomplete and has logic errors.
                    // It only checks for uppercase and lowercase letters and returns false for anything else.
                    // A more robust validation is needed here.
                    function isNumberKey(evt) {
                        var charCode = (evt.which) ? evt.which : event.keyCode;
                        if (charCode > 65 && charCode < 91 || charCode > 96 && charCode < 122) {
                            return true;
                        } else {
                            alert("should be alphabet");
                            return false;
                        }
                    }
                </script>
                <script type="text/javascript">
                    function valid() {
                        if (document.form1.brname.value === "") {
                            alert("INVALID BRANCH NAME");
                            return false;
                        }
                        if (document.form1.firstname.value === "") {
                            alert("INVALID FIRST NAME");
                            return false;
                        }
                        if (document.form1.lastname.value === "") {
                            alert("INVALID LAST NAME");
                            return false;
                        }
                        if (document.form1.loginid.value === "") {
                            alert("INVALID LOGIN ID");
                            return false;
                        }
                        if (document.form1.accountpassword.value === "") {
                            alert("INVALID ACCOUNT PASSWORD");
                            return false;
                        }
                        // Note: The original form does not have a 'confirmpassword' field.
                        // This validation will always fail or be impossible.
                        // I have added a new field in the form below to support this check.
                        if (document.form1.confirmpassword.value === "") {
                            alert("INVALID CONFIRM PASSWORD");
                            return false;
                        }
                        if (document.form1.confirmpassword.value !== document.form1.accountpassword.value) {
                            alert("ACCOUNT PASSWORD MISMATCH");
                            return false;
                        }
                        if (document.form1.transactionpassword.value === "") {
                            alert("INVALID TRANSACTION PASSWORD");
                            return false;
                        }
                        // Note: The original form does not have a 'confirmtransactionpassword' field.
                        // This validation will always fail or be impossible.
                        // I have added a new field in the form below to support this check.
                        if (document.form1.confirmtransactionpassword.value === "") {
                            alert("INVALID CONFIRM TRANSACTION PASSWORD");
                            return false;
                        }
                        if (document.form1.transactionpassword.value !== document.form1.confirmtransactionpassword.value) {
                            alert("TRANSACTION PASSWORD MISMATCH");
                            return false;
                        }
                        if (document.form1.accstatus.value === "") {
                            alert("INVALID ACCOUNT STATUS");
                            return false;
                        }
                        if (document.form1.country.value === "") {
                            alert("INVALID COUNTRY");
                            return false;
                        }
                        if (document.form1.state.value === "") {
                            alert("INVALID STATE");
                            return false;
                        }
                        if (document.form1.city.value === "") {
                            alert("INVALID CITY");
                            return false;
                        }
                    }
                </script>
                <div class="dt-card__body pb-3">
                    <form onsubmit="return valid()" id="form1" name="form1" method="post" action="">
                        <p>&nbsp;<?php echo $logmsg; ?></p>
                        <div class="row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Add Bank Branch</label>
                                    <select name="brname" id="brname" class="custom-select custom-select-sm" required>
                                        <option value="">Select Branch</option>
                                        <?php
                                        while ($rta = mysqli_fetch_assoc($resq)) {
                                            echo "<option value='" . htmlspecialchars($rta['ifsccode']) . "'>" . htmlspecialchars($rta['branchname']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Customer's First Name</label>
                                    <input required name="firstname" id="firstname" class="form-control">
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Customer's Last Name</label>
                                    <input type="text" name="lastname" id="lastname" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Customer's Phone</label>
                                    <input type="number" name="phone" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Customer's Email</label>
                                    <input type="email" name="email" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Select Country</label>
                                    <select name="country" id="country" class="custom-select custom-select-sm" required>
                                        <option value="">Select</option>
                                        <option value="Afganistan">Afghanistan</option>
                                        <option value="Albania">Albania</option>
                                        <option value="Nigeria">Nigeria</option>
                                        <option value="United States of America">United States of America</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Enter State</label>
                                    <input name="state" id="state" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Enter City</label>
                                    <input name="city" id="city" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Account Number</label>
                                    <?php $tcode = str_pad(mt_rand(1111111111, 9999999999), 10, '0', STR_PAD_LEFT); ?>
                                    <input type="number" readonly value="<?php echo htmlspecialchars($tcode); ?>" name="acc" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Login ID</label>
                                    <?php $loginid = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz01234567890'), 0, 14); ?>
                                    <input name="loginid" value="<?php echo htmlspecialchars($loginid); ?>" id="loginid" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Login Password</label>
                                    <?php $loginpass = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz01234567890'), 0, 14); ?>
                                    <input type="text" value="<?php echo htmlspecialchars($loginpass); ?>" name="accountpassword" id="accountpassword" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Confirm Login Password</label>
                                    <input type="text" name="confirmpassword" id="confirmpassword" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Transaction Password</label>
                                    <?php $transpass = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz01234567890'), 0, 14); ?>
                                    <input type="text" value="<?php echo htmlspecialchars($transpass); ?>" name="transactionpassword" id="transactionpassword" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Confirm Transaction Password</label>
                                    <input type="text" name="confirmtransactionpassword" id="confirmtransactionpassword" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Select Account Status</label>
                                    <select name="accstatus" id="accstatus" class="custom-select custom-select-sm" required>
                                        <option value="">Select</option>
                                        <option value="active">Active</option>
                                        <option value="inactive">In-active</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Account Opening Date</label>
                                    <input type="date" name="accopendate" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Select Account Type</label>
                                    <select name="acctype" class="custom-select custom-select-sm" required>
                                        <?php
                                        while ($a = mysqli_fetch_assoc($re)) {
                                            echo "<option value='" . htmlspecialchars($a['accounttype']) . "'>" . htmlspecialchars($a['accounttype']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Opening Balance</label>
                                    <input type="number" name="balance" id="balance" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Date Of Birth</label>
                                    <input type="date" name="dob" id="dob" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Gender</label>
                                    <select name="gender" id="gender" class="custom-select custom-select-sm" required>
                                        <option value="male">Male</option>
                                        <option value="female">Female</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6" style="display: none;">
                                <div class="form-group">
                                    <?php $cot = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); ?>
                                    <input type="text" value="<?php echo htmlspecialchars($cot); ?>" name="cot" class="form-control">
                                </div>
                            </div>
                            <div class="col-sm-6" style="display: none;">
                                <div class="form-group">
                                    <?php $imf = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); ?>
                                    <input type="text" value="<?php echo htmlspecialchars($imf); ?>" name="imf" class="form-control">
                                </div>
                            </div>
                            <div class="col-sm-6" style="display: none;">
                                <div class="form-group">
                                    <?php $activationcode = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); ?>
                                    <input type="text" value="<?php echo htmlspecialchars($activationcode); ?>" name="activationcode" class="form-control">
                                </div>
                            </div>
                            <div class="col-sm-6" style="display: none;">
                                <div class="form-group">
                                    <?php $taxcode = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); ?>
                                    <input type="text" value="<?php echo htmlspecialchars($taxcode); ?>" name="taxcode" class="form-control">
                                </div>
                            </div>

                            <div class="col-sm-6" style="display: none;">
                                <div class="form-group">
                                    <?php $cardLongDigit = str_pad(mt_rand(0, 9999999999999999), 16, '0', STR_PAD_LEFT); ?>
                                    <input type="text" class="form-control" name="card_long_digit" value="<?= htmlspecialchars($cardLongDigit); ?>">
                                </div>
                            </div>

                            <div class="col-sm-6" style="display: none;">
                                <div class="form-group">
                                    <?php
                                    $currentYear = date('Y');
                                    $expiryYear = $currentYear + 4;
                                    $month = str_pad(mt_rand(1, 12), 2, '0', STR_PAD_LEFT);
                                    $expiryYearShort = substr($expiryYear, -2);
                                    $validThru = "$month/$expiryYearShort";
                                    ?>
                                    <input type="text" class="form-control" name="valid_thru" value="<?= htmlspecialchars($validThru); ?>">
                                </div>
                            </div>

                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Account Pin</label>
                                    <?php $otp = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT); ?>
                                    <input type="text" class="form-control" name="otp" value="<?= htmlspecialchars($otp); ?>">
                                </div>
                            </div>
                        </div>
                        </div>
                <div class="px-7 py-5 border-top border-width-2 border-black-transparent">
                    <tr>
                        <td colspan="2">
                            <div align="right">
                                <input type="submit" name="button" id="button" class="btn btn-secondary" value="Create Account" />
                            </div>
                        </td>
                    </tr>
                </div>
                </form>
            </div>
            </div>
        <div class="dt-entry__header">
        </div>
        </div>
    <link rel="stylesheet" href="css/cus.css">
    <?php include'footer.php' ?>
    </body>