<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


include("check_installation.php");

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

// Fetch branches for the dropdown
$branches = [];
$stmt_branch = $con->prepare("SELECT ifsccode, branchname FROM branch");
$stmt_branch->execute();
$result_branch = $stmt_branch->get_result();
while ($row = $result_branch->fetch_assoc()) {
    $branches[] = $row;
}
$stmt_branch->close();


// Fetch account types from the accountmaster table
$account_types = [];
$stmt_acctype = $con->prepare("SELECT accounttype FROM accountmaster");
$stmt_acctype->execute();
$result_acctype = $stmt_acctype->get_result();
while ($row = $result_acctype->fetch_assoc()) {
    $account_types[] = $row['accounttype'];
}
$stmt_acctype->close();



if (isset($_POST["button"])) {
    // Sanitize and validate input
    $accountno = htmlspecialchars($_POST['acc']);
    $cot = htmlspecialchars($_POST['cot']);
    $imf = htmlspecialchars($_POST['imf']);
    $phone = htmlspecialchars($_POST['phone']);
    $email = htmlspecialchars($_POST['email']);
    $acctype = htmlspecialchars($_POST['acctype']);
    $ifsccode = htmlspecialchars($_POST['brname']);
    $firstname = htmlspecialchars($_POST['firstname']);
    $lastname = htmlspecialchars($_POST['lastname']);
    $loginid = htmlspecialchars($_POST['loginid']);
    $accpassword = htmlspecialchars($_POST['accountpassword']);
    $transpassword = htmlspecialchars($_POST['transactionpassword']);
    $accstatus = htmlspecialchars($_POST['accstatus']);
    $country = htmlspecialchars($_POST['country']);
    $state = htmlspecialchars($_POST['state']);
    $city = htmlspecialchars($_POST['city']);
    $accopendate = htmlspecialchars($_POST['accopendate']);
    $dob = htmlspecialchars($_POST['dob']);
    $gender = htmlspecialchars($_POST['gender']);
    $activationcode = htmlspecialchars($_POST['activationcode']);
    $taxcode = htmlspecialchars($_POST['taxcode']);
    $card_long_digit = htmlspecialchars($_POST['card_long_digit']);
    $valid_thru = htmlspecialchars($_POST['valid_thru']);
    $otp = htmlspecialchars($_POST['otp']);
    $balance = htmlspecialchars($_POST['balance']);

    // Check if login ID already exists
    $stmt_check = $con->prepare("SELECT COUNT(*) FROM customers WHERE loginid = ?");
    $stmt_check->bind_param('s', $loginid);
    $stmt_check->execute();
    $count_result = $stmt_check->get_result();
    $count = $count_result->fetch_row()[0];
    $stmt_check->close();

    if ($count > 0) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Login ID already exists!'];
    } else {
        // Insert new customer record
        $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
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
        $stmt_customer = $con->prepare($sql_customer);
        $stmt_customer->bind_param(
            'ssssssssssssssssssssssss',
            $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
        );

        if ($stmt_customer->execute()) {
            $customer_id = $con->insert_id;

            // Insert new account record
            $sql_account = "INSERT INTO accounts (accno, customerid, accstatus, accopendate, accounttype, accountbalance) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt_account = $con->prepare($sql_account);
            $stmt_account->bind_param('sissss', $accountno, $customer_id, $accstatus, $accopendate, $acctype, $balance);
            
            if ($stmt_account->execute()) {
                $_SESSION['message'] = ['type' => 'success', 'text' => "Account created successfully! The account number is: $accountno"];
            } else {
                $_SESSION['message'] = ['type' => 'error', 'text' => 'Error creating account: ' . $con->error];
            }
            $stmt_account->close();
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Error creating customer: ' . $con->error];
        }
        $stmt_customer->close();
    }
    // Redirect to prevent form resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Create New Customer</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <meta name="description" content="Create New Customer">

    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">

    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
	<link rel="stylesheet" type="text/css" href="assets/vendor/choices/css/choices.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>

<body>

<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">New Customer</h1>
                    </div>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">Create New Customer</h5>
                </div>

                <div class="card-body">
                    <?php if (isset($_SESSION['message'])): 
                        $message = $_SESSION['message'];
                        // Unset the session variable after displaying it
                        unset($_SESSION['message']);
                    ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    icon: '<?= $message['type']; ?>',
                                    title: '<?= $message['type'] === 'success' ? 'Success!' : 'Error!'; ?>',
                                    text: '<?= $message['text']; ?>',
                                    confirmButtonText: 'OK'
                                });
                            });
                        </script>
                    <?php endif; ?>
                    
                    <form method="post" action="">
                        <div class="row">
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label>Add Bank Branch</label>
                                    <select name="brname" id="brname" class="form-select js-choice" data-search-enabled="true" required>
                                        <option value="">Select Branch</option>
                                        <?php foreach ($branches as $branch): ?>
                                            <option value="<?= htmlspecialchars($branch['ifsccode']); ?>">
                                                <?= htmlspecialchars($branch['branchname']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Customer's First Name</label>
                                    <input type="text" name="firstname" id="firstname" class="form-control" required>
                                </div>
                            </div>

                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Customer's Last Name</label>
                                    <input type="text" name="lastname" id="lastname" class="form-control" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Customer's Phone</label>
                                    <input type="tel" name="phone" class="form-control" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Customer's Email</label>
                                    <input type="email" name="email" class="form-control" required>
                                </div>
                            </div>

                            <div class="col-sm-6 mb-3">
    <div class="form-group">
        <label class="form-label">Select Account Type</label>
        <select name="acctype" id="acctype" class="form-select js-choice" data-search-enabled="true" required>
            <option value="">Select Account Type</option>
            <?php foreach ($account_types as $type): ?>
                <option value="<?= htmlspecialchars($type); ?>">
                    <?= htmlspecialchars($type); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
</div>


                           <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Select Country</label>
                                    <select id="country" name="country" class="form-control" required>
                                        <option value="">Loading...</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Select State</label>
                                    <select id="state" name="state" class="form-control" required>
                                        <option value="">Select country first</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Select City</label>
                                    <select id="city" name="city" class="form-control" required>
                                        <option value="">Select state first</option>
                                    </select>
                                </div>
                            </div>



                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Date of Birth</label>
                                    <input type="date" name="dob" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Gender</label>
                                    <select name="gender"class="form-select js-choice" data-search-enabled="true" required>
                                        <option value="Male">Male</option>
                                        <option value="Female">Female</option>
                                        <option value="Other">Other</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Account Number</label>
                                    <input type="text" name="acc" value="<?= rand(1000000000, 9999999999); ?>" class="form-control" readonly required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3" style="display:none;">
                                <div class="form-group">
                                    <label class="form-label">Login ID</label>
                                    <input type="text" name="loginid" value="<?= substr(str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789'), 0, 14); ?>" class="form-control" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Login Password</label>
                                    <input type="text" name="accountpassword" value="<?= substr(str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789'), 0, 14); ?>" class="form-control" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Transaction Password</label>
                                    <input type="text" name="transactionpassword" value="<?php echo str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT); ?>" class="form-control" maxlength="4"pattern="\d{4}" inputmode="numeric" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Select Account Status</label>
                                    <select name="accstatus" id="accstatus" class="form-select js-choice" data-search-enabled="true" 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 class="form-label">Account Opening Date</label>
                                    <input type="date" name="accopendate" placeholder="Account Opening Date" class="form-control" required>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Initial Deposit</label>
                                    <input type="text" name="balance" class="form-control amount-input" required>
                                </div>
                            </div>

                           <?php 
$cot = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); 
$imf = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); 
$activationcode = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); 
$taxcode = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'), 0, 10); 
$cardLongDigit = str_pad(mt_rand(0, 9999999999999999), 16, '0', STR_PAD_LEFT); 

// Valid Thru
$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";

// OTP
$otp = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT); 
?>

<input type="hidden" name="cot" value="<?php echo $cot ?>">
<input type="hidden" name="imf" value="<?php echo $imf ?>">
<input type="hidden" name="activationcode" value="<?php echo $activationcode ?>">
<input type="hidden" name="taxcode" value="<?php echo $taxcode ?>">
<input type="hidden" name="card_long_digit" value="<?php echo $cardLongDigit ?>">
<input type="hidden" name="valid_thru" value="<?php echo $validThru ?>">
<input type="hidden" name="otp" value="<?php echo $otp ?>">


                        </div>
                        
                        <div class="pt-3">
                            <div class="">
                                <button type="submit" name="button" class="btn btn-primary">Create Customer</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="assets/vendor/choices/js/choices.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    let countrySelect = document.getElementById("country");
    let stateSelect   = document.getElementById("state");
    let citySelect    = document.getElementById("city");

    // Load countries
    fetch("https://countriesnow.space/api/v0.1/countries/positions")
        .then(res => res.json())
        .then(data => {
            countrySelect.innerHTML = "<option value=''>Select Country</option>";
            data.data.forEach(c => {
                countrySelect.innerHTML += `<option value="${c.name}">${c.name}</option>`;
            });
        });

    // When country is selected → load states
    countrySelect.addEventListener("change", function () {
        let country = this.value;
        stateSelect.innerHTML = "<option value=''>Loading...</option>";
        citySelect.innerHTML = "<option value=''>Select state first</option>";

        fetch("https://countriesnow.space/api/v0.1/countries/states", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ country: country })
        })
        .then(res => res.json())
        .then(data => {
            stateSelect.innerHTML = "<option value=''>Select State</option>";
            if (data.data && data.data.states) {
                data.data.states.forEach(s => {
                    stateSelect.innerHTML += `<option value="${s.name}">${s.name}</option>`;
                });
            }
        });
    });

    // When state is selected → load cities
    stateSelect.addEventListener("change", function () {
        let state = this.value;
        let country = countrySelect.value;
        citySelect.innerHTML = "<option value=''>Loading...</option>";

        fetch("https://countriesnow.space/api/v0.1/countries/state/cities", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ country: country, state: state })
        })
        .then(res => res.json())
        .then(data => {
            citySelect.innerHTML = "<option value=''>Select City</option>";
            if (data.data) {
                data.data.forEach(city => {
                    citySelect.innerHTML += `<option value="${city}">${city}</option>`;
                });
            }
        });
    });
});
</script>

<script>
    document.querySelectorAll('.amount-input').forEach(function(amountInput) {
        amountInput.addEventListener('input', function(e) {
            let value = e.target.value;
            value = value.replace(/[^0-9.]/g, '');
            value = value.replace(/(\..*)\./g, '$1');
            if (value.startsWith('.')) {
                value = '0' + value;
            }
            const parts = value.split('.');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            e.target.value = parts.join('.');
        });
    });
</script>

</body>
</html>