<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Associate']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) && !isset($_SESSION['uref_code']) ) {
        header("Location: logout.php");
        exit();
    }
    
    if(isset($_GET["user"])){
        $userId = $_GET["user"];
        $user_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$userId' ");
        if($user_row = mysqli_fetch_assoc($user_sql)){
            $userName = $user_row["uname"];
            $usertype = $user_row["utype"];
        }
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_run = mysqli_query($con, "SELECT * FROM payment_history WHERE phid = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                        $fran_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$edit_row[ph_for]'");
                        if($fran_row = mysqli_fetch_assoc($fran_sql)){
                            $franName = $fran_row["uname"];
                        }           
                    ?>
                <div class="card">
                    <div class="card-header">
                        <h4 class="m-0">Edit Payment Details For <?php echo $franName?></h4>
                    </div>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="ph_for" class="form-label">RA Name</label>
                                    <select name="ph_for" class="form-control">
                                        <option value="<?php echo $edit_row["ph_for"]; ?>"><?php echo $franName; ?>
                                        </option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="ph_amount" class="form-label">Payment Amount</label>
                                    <input type="text" class="form-control" name="ph_amount"
                                        value="<?php echo $edit_row["ph_amount"]?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="logo" class="form-label">Upload Document <a
                                            href='<?php echo $edit_row["ph_doc"];?>' title='Click to open'
                                            target='_blank'>
                                            (<b>View Uploaded - <img src='<?php echo $edit_row["ph_doc"];?>' height='20'
                                                    data-toggle='modal' data-target='#show-img' class='showModal'>
                                            </b></a> )</label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        placeholder="Upload logo">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="ph_des" class="form-label">Payout Description</label>
                                    <textarea name="ph_des"
                                        class="form-control"><?php echo $edit_row["ph_des"];?></textarea>
                                </div>
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-success btn-user m-2" name="edit_blog">
                                        <i class="fa fa-edit"></i> Update
                                    </button>
                                    <?php if(isset($usertype) && $usertype == 'Franchiee'){?>
                                    <a href="payout.php?user=<?php echo $userId;?>&show_list"
                                        class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                                        Cancel </a>
                                    <?php }else{?>
                                    <a href="payout.php?show_list" class="btn btn-warning btn-user m-2"> <i
                                            class="fas fa-ban"></i>
                                        Cancel </a>
                                    <?php }?>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["view_id"])){
                    $view_sql = "SELECT * FROM payment_history WHERE phid='$_GET[view_id]'";
                    $view_data = mysqli_query($con,$view_sql);
                    if($view_rows = mysqli_fetch_array($view_data)){
                        $fran_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$view_rows[ph_for]'");
                        if($fran_row = mysqli_fetch_assoc($fran_sql)){
                            $franName = $fran_row["uname"];
                        }
                    ?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="m-0">Payout For : <span class="underline"><?php echo $franName; ?></span></h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <?php
                                if (!empty($view_rows['ph_doc']))
                                {
                            ?>
                            <h5 class="underline">Payout Image</h5>
                            <a href='<?php echo $view_rows["ph_doc"];?>' title='Click to open' target='_blank'>
                                (<b>Already Uploaded - <img src='<?php echo $view_rows["ph_doc"];?>' height='50'
                                        data-toggle='modal' data-target='#show-img' class='showModal'>
                                </b> Click To View</a> )
                            <?php }
                                if (!empty($edit_row['ph_doc']))
                                { 
                            ?>
                            <a href='<?php echo $view_rows["ph_doc"];?>' title='Click to open' target='_blank'>
                                (<b>Already Uploaded - <img src='<?php echo $view_rows["ph_doc"];?>' height='50'
                                        data-toggle='modal' data-target='#show-img' class='showModal'>
                                </b> Click To View</a> )
                            <?php } ?>
                        </div>
                        <p><strong>Payout Amount : </strong><?php echo $view_rows['ph_amount']; ?></p>
                        <hr>
                        <p class="m-0"><strong>Payout Descrption :</strong></p>
                        <div class="mb-2" id="ck-img-preview">
                            <?php echo $view_rows["ph_des"];?>
                        </div>
                        <p><strong>Payout by : </strong><?php echo $_SESSION["uname"]; ?></p>
                        <hr>
                        <?php if(isset($usertype) && $usertype == 'subFranchiee'){?>
                        <a href="payout.php?user=<?php echo $userId;?>&show_list" class="btn btn-warning btn-user m-2">
                            <i class="fas fa-ban"></i>
                            Cancel </a>
                        <?php }else{?>
                        <a href="payout.php?show_list" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                            Cancel </a>
                        <?php }?>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["add_new"])){?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="card-title mb-0">Add New Payout</h4>
                    </div>
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="data_up_for" class="form-label">Select Payout Sub Associate</label>
                                    <div class="form-group">
                                        <input type="text" list="Franchisee" class="form-control" id="franValue"
                                            placeholder="Select From List" oninput="setFranchiseeId()">
                                        <datalist id="Franchisee">
                                            <?php 
                                                $sql = "SELECT uid, uname FROM users WHERE admin_ref = '{$_SESSION['uref_code']}' AND utype = 'Sub Associate' ORDER BY uname ASC";
                                                $res = mysqli_query($con, $sql);
                                                while ($row = mysqli_fetch_assoc($res)) {
                                            ?>
                                            <option value="<?php echo $row['uname']; ?>"
                                                data-id="<?php echo $row['uid']; ?>">
                                                <?php echo $row['uname']; ?>
                                            </option>
                                            <?php } ?>
                                        </datalist>

                                        <!-- Hidden input to store data-id value -->
                                        <input type="hidden" name="ph_for" id="ph_for">
                                    </div>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="ph_amount" class="form-label">Payout Amount</label>
                                    <input type="text" name="ph_amount" class="form-control"
                                        placeholder="Enter Payout Amount">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="logo" class="form-label">Upload Document</label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        placeholder="Upload logo">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="ph_des" class="form-label">Payout Description</label>
                                    <textarea name="ph_des" class="form-control"
                                        placeholder="Enter Payout Description"></textarea>
                                </div>
                                <div class="mb-3">
                                    <button class="btn btn-success text-white me-md-2" name="addsubmit" type="submit">
                                        <i class="fa fa-paper-plane"></i> Submit
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }?>
                <?php if(isset($_GET["show_list"])){?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-5">
                                <h4 class="text-gray-800">Sub Associate Payout List</h4>
                            </div>
                            <div class="col-md-7 d-block d-lg-flex justify-content-end">
                                <div class="d-flex justify-content-between mb-2">
                                    <?php if(isset($usertype) && $usertype == 'Sub Associate'){?>
                                    <a class="btn btn-primary btn-sm"
                                        href="payout.php?user=<?php echo $userId;?>&add_new"><i class="fa fa-plus"></i>
                                        Add Payment</a>
                                    <a href="view-franchiee.php#franchisee<?php echo $userId;?>"
                                        class="btn btn-warning text-white btn-sm"><i class="fa fa-arrow-left"></i>
                                        Back</a>
                                    <?php } else{?>
                                    <a class="btn btn-primary btn-sm" href="payout.php?add_new"><i
                                            class="fa fa-plus"></i>
                                        Add Payment</a>
                                    <a href="index.php" class="btn btn-warning text-white btn-sm"><i
                                            class="fa fa-arrow-left"></i>
                                        Back</a>
                                    <?php }?>
                                </div>
                                <?php if(!isset($usertype)){?>
                                <div class="d-flex">
                                    <div style="width: 100%;">
                                        <div class="form-group">
                                            <input type="text" list="Franchisee" class="form-control form-control-sm"
                                                id="franValue" placeholder="Select From List"
                                                oninput="setFranchiseeId()">
                                            <datalist id="Franchisee">
                                                <?php 
                                                    $sql = "SELECT uid, uname FROM users WHERE admin_ref = '{$_SESSION['uref_code']}' AND utype = 'Sub Associate' ORDER BY uname ASC";
                                                    $res = mysqli_query($con, $sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['uname']; ?>"
                                                    data-id="<?php echo $row['uid']; ?>">
                                                    <?php echo $row['uname']; ?>
                                                </option>
                                                <?php } ?>
                                            </datalist>

                                            <!-- Hidden input to store data-id value -->
                                            <input type="hidden" name="ph_for" id="ph_for">
                                        </div>
                                    </div>
                                    <div class="#">
                                        <button type="button" id="filter" class="btn btn-primary btn-sm"> Search
                                        </button>
                                    </div>
                                </div>
                                <?php }?>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding-left: 0;">
                                    <?php
                                    for ($count = 0; $count < 4; $count++) {
                                        echo '<li>
                                        <div class="ph-item">
                                        <div cl ass="ph-test">
                                        <div class="ph-row">
                                        <div class="ph-col-12 big"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        </div>
                                        </div>
                                        </div>
                                        </li>';
                                        }
                                    ?>
                                </ul>
                            </div>

                            <!-- loader -->
                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="col-12" id="filter-table" style="display: none;">
                                <ul class="timeline" id="filter-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>

    <script>
    function setFranchiseeId() {
        const franValue = document.getElementById("franValue").value;
        const options = document.querySelectorAll("#Franchisee option");
        const phFor = document.getElementById("ph_for");

        options.forEach(option => {
            if (option.value === franValue) {
                phFor.value = option.getAttribute("data-id");
            }
        });
    }
    </script>

    <script>
    //dropdown TWO filter Start//
    $(document).ready(function() {
        var load_filter_flag = '';
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        <?php if(isset($usertype) && $usertype == 'Associate'){?>
        var data_up_for = '<?php echo $userId;?>';
        <?php }else{?>
        var data_up_for = '';
        <?php }?>


        $("#filter").click(function() {
            FirstFilterValue = $('#ph_for').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            load_filter_flag = 0;
            if (FirstFilterValue != '' || SecondFilterValue != '') {
                //alert(name);
                $.ajax({
                    url: 'payout-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        data_up_for: data_up_for,
                        start: load_filter_flag
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);
                        load_filter_flag += 10;
                    },
                    complete: function(data) {
                        /* Hide loader container */
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Plz Select an Option');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        function loadMoreFilter(start) {
            console.log('Filter' + start);
            if (load_filter_flag > 0) {
                //alert(name);
                $.ajax({
                    url: 'payout-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        data_up_for: data_up_for,
                        start: start
                    },
                    success: function(result) {
                        $('#filter-table-data').append(result);
                        load_filter_flag += 10;
                    }
                });
            }
        }
        // Scroll Loading of Full Data //
        var load_flag = 0;
        loadMore(load_flag);

        function loadMore(start) {
            //console.log('total'+start);
            $.ajax({
                url: 'payout-Ajax.php',
                type: 'POST',
                data: {
                    data_up_for: data_up_for,
                    start: start
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10;
                },
                complete: function(data) {
                    /* Hide loader container */
                    $("#loader").hide();
                }
            });
        }

        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() >= $(document).height() - $('#inner-body').height()) {
                //console.log('call');
                if (load_filter_flag > 0) {
                    loadMoreFilter(load_filter_flag);
                } else {
                    loadMore(load_flag);
                }
            }
        });
    });
    </script>

</body>

</html>


<!-- Add to database-->
<?php
if (isset($_POST['addsubmit'])) {
    $ph_des = mysqli_real_escape_string($con, strip_tags($_POST['ph_des']));
    $ph_for = mysqli_real_escape_string($con, strip_tags($_POST['ph_for']));
    $ph_amount = mysqli_real_escape_string($con, strip_tags($_POST['ph_amount']));

    $prefix = "payout"; // Your prefix
    $random_number = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
    $timestamp = date("YmdHis"); 

    $ref_id = $prefix . $random_number . $timestamp;
    
    $up_date = date("j F, Y, g:i a");
    $recycle = "1";
    $up_by = $_SESSION['uid'];
    $catagory = 'Documents';

    // New File Upload
    $logopath = ''; // Initialize as empty in case no file is uploaded
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/payout/";
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));

        // Generate a unique file name
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;
        $uploadOk = 1;

        // Check if image file is a valid image type
        $check = getimagesize($_FILES["logo"]["tmp_name"]);
        if ($check !== false) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
            echo "<script>alert('File is not an image.');</script>";
        }

        // Check file size (5MB maximum)
        if ($_FILES["logo"]["size"] > 5000000) {
            $uploadOk = 0;
            echo "<script>alert('Sorry, your file is too large.');</script>";
        }

        // Allow certain file formats
        if (!in_array($imageFileType, ["jpg", "png", "jpeg", "gif"])) {
            $uploadOk = 0;
            echo "<script>alert('Only JPG, JPEG, PNG & GIF files are allowed.');</script>";
        }

        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 1) {
            // If everything is ok, try to upload file
            if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
                $logopath = $target_file;
            } else {
                echo "<script>alert('Sorry, there was an error uploading your file.');</script>";
            }
        }
    }

    $courseCatagory_sql = "INSERT INTO payment_history (ph_des, ph_doc, ph_up_by, ph_upDate, ph_recycle, ph_for, ph_amount) VALUES ('$ph_des', '$logopath','$up_by', '$up_date', '$recycle', '$ph_for', '$ph_amount')";

    if (mysqli_query($con, $courseCatagory_sql)) {
        ?>
<?php if(isset($usertype) && $usertype == 'Associate'){?>
<script>
alert("Details Sent Successfully");
window.location = "payout.php?user=<?php echo $_GET['user']; ?>&show_list";
</script>
<?php } else{?>
<script>
alert("Details Sent Successfully");
window.location = "payout.php?show_list";
</script>
<?php }?>
<?php
    } else {
        ?>
<?php if(isset($usertype) && $usertype == 'Associate'){?>
<script>
alert("Something's Wrong");
window.location = "payout.php?user=<?php echo $_GET['user']; ?>&add_new";
</script>
<?php } else{?>
<script>
alert("Something's Wrong");
window.location = "payout.php?add_new";
</script>
<?php }?>
<?php
    }
}
?>



<!-- Edit database  Blog-->
<?php
if (isset($_POST['edit_blog'])) {
    $ph_des = mysqli_real_escape_string($con, strip_tags($_POST['ph_des']));
    $ph_amount = mysqli_real_escape_string($con, strip_tags($_POST['ph_amount']));

    // Get existing data for image handling
    $existingImage = $edit_row["ph_doc"];

    // File Upload Logic
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/payout/";
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));

        // Generate a unique file name
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;

        // Validate the file
        $uploadOk = 1;
        $check = getimagesize($_FILES["logo"]["tmp_name"]);
        if ($check === false) {
            $uploadOk = 0;
        }
        if ($_FILES["logo"]["size"] > 5000000) {
            $uploadOk = 0;
        }
        if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
            $uploadOk = 0;
        }

        // Attempt to upload if validations pass
        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
                // Unlink (delete) old image file if it exists
                if (!empty($existingImage) && file_exists($existingImage)) {
                    unlink($existingImage);
                }
                $logopath = $target_file;
            } else {
                echo "<script>alert('Error uploading the new file.');</script>";
            }
        } else {
            echo "<script>alert('File validation failed.');</script>";
        }
    } else {
        // If no new file, keep the old image path
        $logopath = $existingImage;
    }

    // Update the database
    $update_sql = "UPDATE payment_history SET ph_amount = '$ph_amount', ph_doc = '$logopath', ph_des = '$ph_des' WHERE phid = '{$edit_row['phid']}'";

    if (mysqli_query($con, $update_sql)) {
        ?>
<?php if(isset($usertype) && $usertype == 'Associate'){?>
<script>
alert("Details Updated Successfully");
window.location = "payout.php?user=<?php echo $userId;?>&show_list";
</script>
<?php } else{?>
<script>
alert("Details Updated Successfully");
window.location = "payout.php?show_list";
</script>
<?php }?>
<?php
    } else {
        ?>
<?php if(isset($usertype) && $usertype == 'Associate'){?>
<script>
alert("Something went wrong while updating.");
window.location = "payout.php?user=<?php echo $userId;?>&edit";
</script>
<?php } else {?>
<script>
alert("Something went wrong while updating.");
window.location = "payout.php?edit";
</script>
<?php }?>
<?php
    }
}
?>



<!-- Recycle database  payout-->
<?php
  if ( isset($_GET["rec_id"]) ) {
    $find_sql = "SELECT * FROM data WHERE data_sl_no = '$_GET[rec_id]'";
    $find_run = mysqli_query($con, $find_sql);
    if ($f_rows = mysqli_fetch_assoc($find_run)) {
        $old_rec = $f_rows["data_recycle"];
    
        if ($old_rec == 1) {
            $new_rec = 0;
        } elseif ($old_rec == 0) {
            $new_rec = 1;
        }
    
        $update_sql = "UPDATE data SET data_recycle = '$new_rec' WHERE data_sl_no = '$_GET[rec_id]'";
        $update_run = mysqli_query($con, $update_sql);

        if ( $update_run ) {
            ?>
<script>
alert("Sent to Recycle Successfully");
window.location = "payout.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
        } else {
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'payout.php?user=<?php echo $userId;?>&show_list';
}, 1200);
</script>
<?php
        }
        
    }

}
?>


<!-- delete database  Blog-->
<?php
if (isset($_GET["del_id"])) {
    $id = mysqli_real_escape_string($con, $_GET["del_id"]);
    
    $find_sql = "SELECT * FROM data WHERE data_sl_no = '$id'";
    $find_run = mysqli_query($con, $find_sql);

    if ($f_rows = mysqli_fetch_assoc($find_run)) {
        $old_img = $f_rows['data_img'];

        if (!empty($old_img)) {
            $previous_image_path = '../upload/payout/' . $old_img;

            if (file_exists($previous_image_path)) {
                if (unlink($previous_image_path)) {
                    // Image deleted successfully
                } else {
                    // Failed to delete image
                    echo "Error deleting image: " . mysqli_error($con);
                }
            }
        }
    }

    $delete_sql = "DELETE FROM data WHERE data_sl_no = '$id'";
    
    if (mysqli_query($con, $delete_sql)) {
        ?>
<script>
alert("Deleted Successfully");
window.location = "payout.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
    } else {
        ?>
<script>
alert("Failed to delete");
window.location = "payout.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
    }
}
?>