<?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']) ) {
        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"];

            if($usertype == 'subFranchiee'){
                $fran_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '{$user_row["admin_ref"]}' ");
                if($fran_row = mysqli_fetch_assoc($fran_sql)){
                    $franId = $fran_row["uid"];
                }
            }
        }
    }
?>

<!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["user"])){?>
                <div class="card mt-3">
                    <div class="card-header text-center">
                        <h4 class="card-title mb-0">Add Document Of <span
                                style='color:#99c003;'><?php echo $userName; ?></span></h4>
                    </div>
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <input type="hidden" name="data_up_for" class="form-control"
                                    value="<?php echo $userId; ?>">
                                <div class="col-md-6 mb-3">
                                    <label for="data_title" class="form-label">Document Title</label>
                                    <select name="data_title" class="form-control" id="" required>
                                        <option value="">Select Document</option>
                                        <option value="Pan Card">Pan Card</option>
                                        <option value="Votar Card">Votar Card</option>
                                        <option value="Aadhar Card">Aadhar Card</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="logo" class="form-label">Upload Document</label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        placeholder="Upload logo" accept=".jpg, .jpeg, .png, .gif, .pdf" capture
                                        required>
                                </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 }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

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

</body>

</html>


<?php
if (isset($_POST['addsubmit'])) {
    $title = mysqli_real_escape_string($con, strip_tags($_POST['data_title']));
    $data_up_for = mysqli_real_escape_string($con, strip_tags($_POST['data_up_for']));

    $prefix = "uplodDocuments"; // 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 = '';
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/uplodDocuments/";
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));

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

        $uploadOk = 1;

        // Get file MIME type
        $fileType = mime_content_type($_FILES["logo"]["tmp_name"]);

        if ($fileType !== false) {
            // Allow images, PDFs, and document files
            $allowedTypes = [
                'image/jpeg',
                'image/png',
                'image/gif',
                'application/pdf',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            ];

            if (in_array($fileType, $allowedTypes)) {
                $uploadOk = 1;
            } else {
                $uploadOk = 0;
                echo "<script>alert('File type not allowed. Please upload an image (JPEG, PNG, GIF), PDF, or DOC/DOCX file.');</script>";
            }
        } else {
            $uploadOk = 0;
            echo "<script>alert('Unable to determine file type. Please try again.');</script>";
        }

        if ($uploadOk == 1) {
            // Compress Images
            if (in_array($fileType, ['image/jpeg', 'image/png', 'image/gif'])) {
                if (compressImage($_FILES["logo"]["tmp_name"], $target_file, 75)) {
                    $logopath = $target_file;
                } else {
                    echo "<script>alert('Failed to compress and upload image.');</script>";
                }
            } 
            // Compress PDFs
            elseif ($fileType == 'application/pdf') {
                if (compressPDF($_FILES["logo"]["tmp_name"], $target_file)) {
                    $logopath = $target_file;
                } else {
                    echo "<script>alert('Failed to compress and upload PDF.');</script>";
                }
            } 
            // Other files (No compression)
            else {
                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>";
                }
            }
        }
    }

    // Define $short_des, $long_des, and $subCategory as needed or comment them if not used
    $short_des = ''; // or fetch from POST
    $long_des = '';  // or fetch from POST
    $subCategory = 'KYC'; 

    $courseCatagory_sql = "INSERT INTO data (data_ref_id, data_catagory, data_title, data_img, data_short_des, data_long_des, data_up_by, data_up_date, data_recycle, data_subCategory, data_up_for) VALUES ('$ref_id', '$catagory', '$title', '$logopath', '$short_des', '$long_des', '$up_by', '$up_date', '$recycle', '$subCategory', '$data_up_for')";

    if (mysqli_query($con, $courseCatagory_sql)) {
        
        // Update uStatus to Active
        // $updateSql = mysqli_query($con, "UPDATE users SET uStatus = '1' WHERE uid = '$data_up_for'");
        if($usertype == 'subFranchiee'){
            ?>
<script>
alert("Details Sent Successfully");
window.location = "subFranchiee-list.php?franchisee=<?php echo $franId; ?>&show_list";
</script>
<?php } else { ?>
<script>
alert("Details Sent Successfully");
window.location = "uplodDocuments.php?user=<?php echo $data_up_for; ?>&show_list";
</script>
<?php
    }
    } else {
        ?>
<script>
alert("Something's Wrong");
window.location = "view-franchisee.php";
</script>
<?php
    }
}

// Compress image function
function compressImage($source, $destination, $quality) {
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
        return imagejpeg($image, $destination, $quality);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
        return imagepng($image, $destination, floor($quality / 10)); // PNG quality is 0-9
    } elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source);
        return imagegif($image, $destination);
    }

    return false;
}

// Compress PDF function
function compressPDF($source, $destination) {
    $command = "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$destination $source";
    exec($command, $output, $return_var);
    return $return_var == 0;
}
?>