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

include("check_installation.php");
include("fetch_settings.php");


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

$m = date("Y-m-d");

$custid = isset($_GET['custid']) ? intval($_GET['custid']) : 0;

if ($custid > 0) {
    // === FETCH CUSTOMER DETAILS USING PREPARED STATEMENTS ===
    $stmt1 = $con->prepare("SELECT * FROM customers WHERE customerid = ?");
    $stmt1->bind_param("i", $custid);
    $stmt1->execute();
    $results1 = $stmt1->get_result();

    if ($arrow = $results1->fetch_assoc()) {
    $fname = $arrow['firstname'];
    $lname = $arrow['lastname'];
    $phone = $arrow['phone'];
    $email = $arrow['email'];
    $customer = $arrow['customerid'];
    $country = $arrow['country'];
    $city = $arrow['city'];
    $state = $arrow['state'];
    $ifsccode = $arrow['ifsccode'];
    $loginid = $arrow['loginid'];
    $acc = $arrow['acctype'];
    $accp = $arrow['accpassword'];
    $trap = $arrow['transpassword'];
    $accstatus = $arrow['accstatus'];
    $status = $arrow['accstatus'];
    $accopendate = $arrow['accopendate'];
    $lastlogin = $arrow['lastlogin'];
    $dob = $arrow['dob'];
    $gender = $arrow['gender'];
    $valid_thru = $arrow['valid_thru'];

    $cot = $arrow['cot'];
    $imf = $arrow['imf'];
    $taxcode = $arrow['taxcode'];
    $activationcode = $arrow['activationcode'];
    $card_long_digit = $arrow['card_long_digit'];
    $otp = $arrow['otp'];
}
    $stmt1->close();

    // === FETCH ACCOUNT DETAILS USING PREPARED STATEMENTS ===
    $stmt2 = $con->prepare("SELECT * FROM accounts WHERE customerid = ?");
    $stmt2->bind_param("i", $custid);
    $stmt2->execute();
    $results2 = $stmt2->get_result();
    
    if ($arrow = $results2->fetch_assoc()) {
        $acct = $arrow['accounttype'];
        $accountbalance = $arrow['accountbalance'];
    }
    $stmt2->close();
    
    $resultsd = $con->query("SELECT * FROM accounts WHERE customerid = " . $custid);
    $num_rows = $resultsd->num_rows;
}

if (isset($_POST["button"])) {
    // Collect and sanitize form data
    $valid_thru = $_POST['valid_thru']; 
    $otp = $_POST['otp'];
    $card_long_digit = str_replace(' ', '', $_POST['card_long_digit']);

    // Server-side validation
    $errors = [];
    if (!preg_match('/^(0[1-9]|1[0-2])\/([0-9]{2})$/', $valid_thru)) {
        $errors[] = 'Invalid "Valid Thru" format. Please use MM/YY (e.g., 12/25).';
    }
    if (!preg_match('/^\d{6}$/', $otp)) {
        $errors[] = 'OTP must be exactly 6 digits.';
    }
    if (!preg_match('/^\d{16}$/', $card_long_digit)) {
        $errors[] = 'Card Long Digit must be exactly 16 digits.';
    }

    if (empty($errors)) {
        
        $cleaned_balance_string = str_replace(',', '', $_POST['balance']);
       
        $new_account_balance = floatval($cleaned_balance_string);
        
        $all_success = true; 
        $final_error_message = '';

        // --- UPDATE 1: customers table ---
        $sql1 = "UPDATE customers SET country = ?, accstatus = ?, loginid = ?, acctype = ?, accpassword = ?, transpassword = ?, state = ?, city = ?, phone = ?, firstname = ?, lastname = ?, email = ?, gender = ?, dob = ?, valid_thru = ?, cot = ?, imf = ?, activationcode = ?, taxcode = ?, card_long_digit = ?, otp = ? WHERE customerid = ?";
        $stmt3 = $con->prepare($sql1);
        $stmt3->bind_param("sssssssssssssssssssssi",
            $_POST['country'], $_POST['accstatus'], $_POST['loginid'], $_POST['acctype'], $_POST['accountpassword'],
            $_POST['transactionpassword'], $_POST['state'], $_POST['city'], $_POST['phone'], $_POST['fname'],
            $_POST['lname'], $_POST['email'], $_POST['gender'], $_POST['dob'], $valid_thru,
            $_POST['cot'], $_POST['imf'], $_POST['activationcode'], $_POST['taxcode'], $_POST['card_long_digit'],
            $_POST['otp'], $custid
        );

        if (!$stmt3->execute()) {
            $all_success = false;
            $final_error_message .= 'Customer Details Error: ' . $stmt3->error . '<br>';
        }
        $stmt3->close();

        // --- UPDATE 2: accounts table ---
        $sql2 = "UPDATE accounts SET accstatus = ?, accounttype = ?, accountbalance = ? WHERE customerid = ?";
        $stmt4 = $con->prepare($sql2);
        
        $stmt4->bind_param("ssdi", 
            $_POST['accstatus'], $_POST['acctype'], $new_account_balance, $custid
        );

        if (!$stmt4->execute()) {
            $all_success = false;
            $final_error_message .= 'Account Details Error: ' . $stmt4->error;
        }
        $stmt4->close();
        
        // --- SET FINAL SESSION MESSAGE FOR SWEETALERT ---
        if ($all_success) {
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Customer Account and Details Updated Successfully.'];
        } else {
            // If any error occurred, set the error message
            $_SESSION['message'] = ['type' => 'error', 'text' => $final_error_message];
        }

    } else {
        // Validation failed, set session message to show error from validation array
        $error_text = implode('<br>', $errors);
        $_SESSION['message'] = ['type' => 'error', 'text' => $error_text];
    }
    
    
    header("Location: edit_account.php?custid=$custid");
    exit();
}


?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Edit Account</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="">

    <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">Edit Account: <?= htmlspecialchars($fname . ' ' . $lname); ?></h1>
                    </div>
                </div>
            </div>

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

                <div class="card-body">
                    <?php if (isset($_SESSION['message'])): 
                        $message = $_SESSION['message'];
                        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="" id="editForm">
    <input type="hidden" name="current_accno" value="<?= htmlspecialchars($customer); ?>">
    
    <div class="row">
        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">Customer's First Name</label>
                <input type="text" name="fname" id="firstname" class="form-control" value="<?php echo htmlspecialchars($fname); ?>" 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="lname" id="lastname" class="form-control" value="<?php echo htmlspecialchars($lname); ?>" 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" value="<?php echo htmlspecialchars($phone); ?>" 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" value="<?php echo htmlspecialchars($email); ?>" 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>
                    <option value="Savings" <?php echo ($acc == 'Savings') ? 'selected' : ''; ?>>Savings</option>
                    <option value="Current" <?php echo ($acc == 'Current') ? 'selected' : ''; ?>>Current</option>
                    <option value="Fixed Deposit" <?php echo ($acc == 'Fixed Deposit') ? 'selected' : ''; ?>>Fixed Deposit</option>
                </select>
            </div>
        </div>

       <div class="col-sm-6 mb-3">
    <div class="form-group">
        <label class="form-label">Country</label>
        <input type="text" id="country" name="country" class="form-control" value="<?= htmlspecialchars($country); ?>" required>
    </div>
</div>

<div class="col-sm-6 mb-3">
    <div class="form-group">
        <label class="form-label">State</label>
        <input type="text" id="state" name="state" class="form-control" value="<?= htmlspecialchars($state); ?>" required>
    </div>
</div>

<div class="col-sm-6 mb-3">
    <div class="form-group">
        <label class="form-label">City</label>
        <input type="text" id="city" name="city" class="form-control" value="<?= htmlspecialchars($city); ?>" required>
    </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" value="<?= htmlspecialchars($dob); ?>">
            </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" <?= ($gender == 'Male') ? 'selected' : ''; ?>>Male</option>
                    <option value="Female" <?= ($gender == 'Female') ? 'selected' : ''; ?>>Female</option>
                    <option value="Other" <?= ($gender == 'Other') ? 'selected' : ''; ?>>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="<?= htmlspecialchars($loginid)?>" class="form-control" readonly required>
            </div>
        </div>
        
        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">Login ID</label>
                <input type="text" name="loginid" value="<?= htmlspecialchars($loginid); ?>" 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="<?php echo htmlspecialchars($accp);?>" 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 htmlspecialchars($trap);?>" class="form-control" 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" <?= ($accstatus == 'active') ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?= ($accstatus == 'inactive') ? 'selected' : ''; ?>>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" value="<?= htmlspecialchars($accopendate); ?>" required>
            </div>
        </div>
        
        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">Account Balance</label>
                <input type="text" name="balance" class="form-control amount-input" value="<?= number_format($accountbalance, 2); ?>" required>
            </div>
        </div>

       <div class="row mb-3">
    <div class="col-6">
        <button class="btn btn-primary-soft w-100" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFields" aria-expanded="false" aria-controls="advancedFields">
            Show/Hide Additional Account Details
        </button>
    </div>
</div>

<div class="collapse" id="advancedFields">
    <div class="row">
        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">COT</label>
                <input type="text" name="cot" class="form-control" value="<?= htmlspecialchars($cot); ?>" required>
            </div>
        </div>

        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">IMF</label>
                <input type="text" name="imf" class="form-control" value="<?php echo  htmlspecialchars($imf); ?>" required>
            </div>
        </div>

        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">Activation Code</label>
                <input type="text" name="activationcode" class="form-control" value="<?php echo htmlspecialchars($activationcode); ?>" required>
            </div>
        </div>

        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">Tax Code</label>
                <input type="text" name="taxcode" class="form-control" value="<?php echo htmlspecialchars($taxcode); ?>" required>
            </div>
        </div>

        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">Card Long Digit</label>
                <input type="text" name="card_long_digit" class="form-control" value="<?php echo htmlspecialchars($card_long_digit); ?>" required>
            </div>
        </div>
		
		<div class="col-sm-6 mb-3">
    <div class="form-group">
        <label class="form-label">Valid Thru</label>
        <input type="text" name="valid_thru" class="form-control" value="<?php echo htmlspecialchars($valid_thru);?>" required>
    </div>
</div>

        <div class="col-sm-6 mb-3">
            <div class="form-group">
                <label class="form-label">OTP</label>
                <input type="text" name="otp" class="form-control" value="<?php echo htmlspecialchars($otp); ?>" required>
            </div>
        </div>
    </div>
</div>

    </div>
    
    <div class="pt-3">
        <div class="">
            <button type="submit" name="button" class="btn btn-primary">Update 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.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>


<script>
document.getElementById('editForm').addEventListener('submit', function(event) {
    const validThruInput = document.querySelector('input[name="valid_thru"]');
    const otpInput = document.querySelector('input[name="otp"]');
    const cardLongDigitInput = document.querySelector('input[name="card_long_digit"]');

    let isValid = true;
    let errorMessage = '';

    // Valid Thru (MM/YY format)
    const validThruRegex = /^(0[1-9]|1[0-2])\/([0-9]{2})$/;
    if (!validThruRegex.test(validThruInput.value)) {
        isValid = false;
        errorMessage += 'Invalid "Valid Thru" format. Please use MM/YY (e.g., 12/25).\n';
        validThruInput.style.borderColor = 'red';
    } else {
        validThruInput.style.borderColor = '';
    }

    // OTP (6 digits)
    const otpRegex = /^\d{6}$/;
    if (!otpRegex.test(otpInput.value)) {
        isValid = false;
        errorMessage += 'OTP must be exactly 6 digits.\n';
        otpInput.style.borderColor = 'red';
    } else {
        otpInput.style.borderColor = '';
    }

    // Card Long Digit (16 digits)
    const cardRegex = /^\d{16}$/;
    if (!cardRegex.test(cardLongDigitInput.value.replace(/\s/g, ''))) {
        isValid = false;
        errorMessage += 'Card Long Digit must be exactly 16 digits.\n';
        cardLongDigitInput.style.borderColor = 'red';
    } else {
        cardLongDigitInput.style.borderColor = '';
    }

    if (!isValid) {
        event.preventDefault(); // Stop the form from submitting
        Swal.fire({
            icon: 'error',
            title: 'Validation Error',
            text: errorMessage,
            confirmButtonText: 'OK'
        });
    }
});
</script>


</body>
</html>