<?php
// Note: It's recommended to enable error reporting for development: error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
error_reporting(0);
include("../config/theconfig.php");
include("header.php");

$msg = 0;

if (!(isset($_SESSION['customerid']))) {
    header('Location:login.php?error=nologin');
    exit();
}

$dts = date("Y-m-d H:i:s");

// Update last login using a prepared statement
$stmt_lastlogin = mysqli_prepare($con, "UPDATE customers SET lastlogin=? WHERE customerid=?");
if ($stmt_lastlogin) {
    mysqli_stmt_bind_param($stmt_lastlogin, 'ss', $dts, $_SESSION['customerid']);
    mysqli_stmt_execute($stmt_lastlogin);
    mysqli_stmt_close($stmt_lastlogin);
}

// The following queries are currently not used in the display, but are updated for consistency
$sqlq = mysqli_query($con, "SELECT * FROM transaction WHERE paymentstat='Pending'");
$mailreq = mysqli_query($con, "SELECT * FROM mail WHERE reciverid='" . mysqli_real_escape_string($con, $_SESSION['customerid']) . "'");

// Fetch accounts using a prepared statement
$stmt_accounts = mysqli_prepare($con, "SELECT * FROM accounts WHERE customerid=?");
if ($stmt_accounts) {
    mysqli_stmt_bind_param($stmt_accounts, 's', $_SESSION['customerid']);
    mysqli_stmt_execute($stmt_accounts);
    $results = mysqli_stmt_get_result($stmt_accounts);
    $rowrec = []; // Initialize $rowrec outside the loop

    while ($arrow = mysqli_fetch_array($results)) {
        $acno = $arrow['accno'];
        $status = $arrow['accstatus'];
        $accopen = $arrow['accopendate'];
        $acctype = $arrow['accounttype'];
        $accbal = $arrow['accountbalance'];
        $email = $arrow['email'];
        $phone = $arrow['phone'];
    }
    mysqli_stmt_close($stmt_accounts);
}

// Fetch customer details using a prepared statement
$stmt_customers = mysqli_prepare($con, "SELECT * FROM customers WHERE customerid=?");
if ($stmt_customers) {
    mysqli_stmt_bind_param($stmt_customers, 's', $_SESSION['customerid']);
    mysqli_stmt_execute($stmt_customers);
    $result = mysqli_stmt_get_result($stmt_customers);
    $rowrec = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt_customers);
}

// File upload logic
if (isset($_POST['uploadbtn'])) {
    // Check if the file was uploaded without errors
    if (isset($_FILES['product_img1']) && $_FILES['product_img1']['error'] === UPLOAD_ERR_OK) {
        $product_img1 = $_FILES['product_img1']['name'];
        $tmp_name1 = $_FILES['product_img1']['tmp_name'];

        // Move the uploaded file
        if (move_uploaded_file($tmp_name1, "assets/images/users/$product_img1")) {
            // Update the database using a prepared statement to prevent SQL injection
            $stmt_update = mysqli_prepare($con, "UPDATE customers SET image=? WHERE customerid=?");
            if ($stmt_update) {
                mysqli_stmt_bind_param($stmt_update, 'ss', $product_img1, $_SESSION['customerid']);
                if (mysqli_stmt_execute($stmt_update)) {
                    $msg = 1;
                    echo "<script> window.open('dashboard.php','_self') </script>";
                } else {
                    // Handle database update error
                    echo "<div class='alert alert-danger'>Database update failed: " . mysqli_error($con) . "</div>";
                }
                mysqli_stmt_close($stmt_update);
            } else {
                // Handle prepare statement error
                echo "<div class='alert alert-danger'>Prepare statement failed: " . mysqli_error($con) . "</div>";
            }
        } else {
            // Handle file move error
            echo "<div class='alert alert-danger'>Failed to move uploaded file.</div>";
        }
    } else {
        // Handle file upload errors
        echo "<div class='alert alert-danger'>File upload failed with error code: " . $_FILES['product_img1']['error'] . "</div>";
    }
}
?>

<body data-sidebar="dark">

    <div id="layout-wrapper">
        <div class="main-content">

            <div class="page-content">
                <div class="container-fluid">

                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0 font-size-18">Profile Image</h4>

                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="javascript: void(0);">Dasboard</a></li>
                                        <li class="breadcrumb-item active">Upload Image</li>
                                    </ol>
                                </div>

                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">Profile Image</h5>

                                    <?php
                                    if ($msg == '1') {
                                        echo '<div class="alert alert-success"> Profile Image Uploaded Successfully ! </div>';
                                    }
                                    ?>
                                    <form method="POST" action="" enctype="multipart/form-data">

                                        <div class="mb-3">
                                            <label> Choose Image </label>
                                            <input type="file" required name="product_img1" id="product_img1" class="form-control">
                                        </div>

                                        <button type="submit" class="btn btn-light waves-effect waves-light w-sm" name="uploadbtn" id="uploadbtn">
                                            <i class="mdi mdi-upload d-block font-size-16"></i> Upload
                                        </button>

                                    </form>

                                </div>
                                </div>
                            </div>
                        </div>
                    </div> </div>
            <?php include 'footer.php' ?>

        </div>
        </div>
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/metismenu/metisMenu.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script src="assets/js/pages/dashboard.init.js"></script>
    <script src="assets/js/app.js"></script>

    <script src="assets/libs2/node_modules/datatables.net/js/jquery.dataTables.js"></script>
    <script src="assets/node_modules/libs2/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
    <script src="assets/libs2/custom/data-table.js"></script>

</body>