<?php
// if (session_status() === PHP_SESSION_NONE) {
//     session_start();
// }

// require('../../db.php');
// require('../../shared/functionsinc.php'); 

// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//     try {
//         $updateSuccess = false;
//         $creatorType = ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer')
//             ? 'users'
//             : 'property_users';
//         $userId = $_SESSION['userid'];
//         $userLay = $_SESSION['layer'];
//         $profileData = [];

//         if (isset($_POST["pfname"])) {
//             $fname = $_POST["pfname"];
//             $lname = $_POST["plname"];
//             if ($_SESSION['layer'] === 'property admin' || $_SESSION['layer'] === 'user') {
//                 $mNum = $_POST["mphone"];
//                 $hNum = $_POST["hphone"];
//                 $updateSuccess = updateProfile($pdo, $fname, $lname, $mNum, $hNum);
//             }else {
//                 $updateSuccess = updateProfile($pdo, $fname, $lname, "", "");
//             }

//         }

//         if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {

//             $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
//             $fileMimeType = $_FILES['profile_image']['type']; // Get MIME type from the browser
        
//             if (!in_array($fileMimeType, $allowedMimeTypes)) {
//                 throw new Exception('Invalid image type. Only JPG, PNG, and GIF are allowed.');
//             }
        
//             $maxFileSize = 2 * 1024 * 1024;
//             if ($_FILES['profile_image']['size'] > $maxFileSize) {
//                 throw new Exception('File size exceeds the 2MB limit.');
//             }
        
//             $targetDir = "../../../../data/profile_images/";
        
//             $fileExtension = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
//             $imageFileName = 'user_' . $userId . '_profile_' . time() . '.' . $fileExtension;
//             $targetFilePath = $targetDir . $imageFileName;

//             if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $targetFilePath)) {
//                 $profileData['location'] = $imageFileName;
//                 $_SESSION['profile_image'] = $imageFileName;
//             } else {
//                 throw new Exception("Failed to upload image.");
//             }
//         }
        
//         if (isset($_POST['avatarIcon']) && empty($profileData['location'])) {
//             $selectedAvatarIcon = $_POST['avatarIcon'];
//             $profileData['location'] = $selectedAvatarIcon;
//             $_SESSION['avatar_icon'] = $selectedAvatarIcon;
//         }

//         if (!empty($profileData['location'])) {
//             try {
//                 $row = fetchDataSingle('profile_photo', ['user_id' => $userId, 'creator_type' => $creatorType]);

//                 if ($row) {
//                     $stmt = $pdo->prepare("UPDATE profile_photo SET location = ? WHERE user_id = ? AND creator_type = ?");
//                     $stmt->execute([$profileData['location'], $userId, $creatorType]);
//                 } else {
//                     $stmt = $pdo->prepare("INSERT INTO profile_photo (user_id, location, created_by, creator_type) VALUES (?, ?, ?, ?)");
//                     $stmt->execute([$userId, $profileData['location'], $userId, $creatorType]);
//                 }
//             } catch (PDOException $e) {

//                 $_SESSION['alert'] = [
//                     "message" => "Database error: " . $e->getMessage(),
//                     "type" => "danger"
//                 ];
//                 header("Location: ../../dashboard.php");
//                 exit();
//             }
//         }

//         if (isset($_POST['delete_image']) && $_POST['delete_image'] == 1) {
//             try {
//                 $creatorType = ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer')
//                     ? 'users'
//                     : 'property_users';

//                 $row = fetchDataSingle('profile_photo', ['user_id' => $_SESSION['userid'], 'creator_type' => $creatorType]);

//                 if ($row && strpos($row['location'], 'fa-') !== 0) {

//                     $filePath = "../../../../data/profile_images/" . $row['location'];
//                     if (file_exists($filePath)) {
//                         unlink($filePath);
//                     }

//                     $stmt = $pdo->prepare("UPDATE profile_photo SET location = '' WHERE user_id = ? AND creator_type = ?");
//                     $stmt->execute([$_SESSION['userid'], $creatorType]);

//                     unset($_SESSION['profile_image']);
//                 }

//                 $_SESSION['alert'] = [
//                     "message" => "Profile image deleted successfully.",
//                     "type" => "success"
//                 ];
//             } catch (Exception $e) {
//                 $_SESSION['alert'] = [
//                     "message" => "An error occurred while deleting the profile image: " . $e->getMessage(),
//                     "type" => "danger"
//                 ];
//             }

//             header("Location: ../../dashboard.php");
//             exit();
//         }

//         if (isset($_POST['changePasswordSubmit'])) {
//             $newPassword = $_POST['newPassword'];
//             $confirmPassword = $_POST['confirmPassword'];

//             if ($newPassword !== $confirmPassword) {
//                 $_SESSION['alert'] = [
//                     "message" => "Passwords do not match.",
//                     "type" => "danger"
//                 ];
//                 header("Location: ../../dashboard.php");
//                 exit();
//             }

//             $passwordPattern = '/^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]).{8,}$/';
//             if (!preg_match($passwordPattern, $newPassword)) {
//                 $_SESSION['alert'] = [
//                     "message" => "Password must be at least 8 characters, include 1 uppercase letter, 1 number, and 1 special character.",
//                     "type" => "danger"
//                 ];
//                 header("Location: ../../dashboard.php");
//                 exit();
//             }

//             try {
//                 $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);

//                 if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer' || $_SESSION['layer'] === 'organization admin') {
//                     updateTable('users', 
//                         ['password' => $hashedPassword], 
//                         'id = :id', 
//                         ['id' => $_SESSION['userid']]
//                     );
//                 } else {
//                     updateTable('property_users', 
//                         ['password' => $hashedPassword], 
//                         'id = :id', 
//                         ['id' => $_SESSION['userid']]
//                     );
//                 }

//                 $_SESSION['alert'] = [
//                     "message" => "Password updated successfully.",
//                     "type" => "success"
//                 ];
//             } catch (Exception $e) {
//                 $_SESSION['alert'] = [
//                     "message" => "An error occurred while updating the password: " . $e->getMessage(),
//                     "type" => "danger"
//                 ];
//             }

//             header("Location: ../../dashboard.php");
//             exit();
//         }

//         header("Location: ../../dashboard.php");
//         exit();

//     } catch (Exception $e) {

//         $_SESSION['alert'] = [
//             "message" => "An error occurred: " . $e->getMessage(),
//             "type" => "danger"
//         ];
//         header("Location: ../../dashboard.php");
//         exit();
//     }
// }

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require('../../db.php');
require('../../shared/functionsinc.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // var_dump($_SESSION);
    // exit();
    try {
        $updateSuccess = false;
        if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
            $creator_type = 'users';
        }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
            $creator_type = 'dealer_admins';
            $photo_loc = $_SESSION['photo_loc'];
        }else {
            $creator_type = 'property_users';
            $photo_loc = $_SESSION['photo_loc'];
        }
        $userId = $_SESSION['userid'];
        $currentProperty = $_SESSION['property'];
        $isMultiPropUser = $_SESSION['isMultiPropUser'] ?? false;

        $profileData = [];

        // Update profile details
        if (isset($_POST["pfname"])) {
            $fname = $_POST["pfname"];
            $lname = $_POST["plname"];

            if ($isMultiPropUser) {
                $mNum = preg_replace('/\D/', '', $_POST["mphone"]);
                $hNum = preg_replace('/\D/', '', $_POST["hphone"]);
                $updateSuccess = updateMultiPropProfile($userId, $currentProperty, $fname, $lname, $mNum, $hNum);
            } elseif ($_SESSION['layer'] === 'property admin' || $_SESSION['layer'] === 'user') {
                $mNum = preg_replace('/\D/', '', $_POST["mphone"]);
                $hNum = preg_replace('/\D/', '', $_POST["hphone"]);
                $updateSuccess = updateProfile($pdo, $fname, $lname, $mNum, $hNum);
            } else {
                $updateSuccess = updateProfile($pdo, $fname, $lname, "", "");
            }
        }

        // Update profile image
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
            $fileMimeType = $_FILES['profile_image']['type'];

            if (!in_array($fileMimeType, $allowedMimeTypes)) {
                throw new Exception('Invalid image type. Only JPG, PNG, and GIF are allowed.');
            }

            $maxFileSize = 4 * 1024 * 1024;
            if ($_FILES['profile_image']['size'] > $maxFileSize) {
                return ["success" => false, "error" => "File size exceeds the 4MB limit."];
            }

            $targetDir = "../../../../data/profile_images/";
            $fileExtension = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
            $imageFileName = 'user_' . $userId . '_profile_' . time() . '.' . $fileExtension;
            $targetFilePath = $targetDir . $imageFileName;

            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $targetFilePath)) {

                chmod($targetFilePath, 0666);

                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                    shell_exec("icacls " . escapeshellarg($targetFilePath) . " /grant Everyone:F");
                }
        
                $profileData['location'] = $imageFileName;
                $_SESSION['profile_image'] = $imageFileName;
            } else {
                throw new Exception("Failed to upload image.");
            }
        }

        // Update avatar icon if no profile image
        // if (isset($_POST['avatarIcon']) && empty($profileData['location'])) {
        //     $selectedAvatarIcon = $_POST['avatarIcon'];
        //     $profileData['location'] = $selectedAvatarIcon;
        //     $_SESSION['avatar_icon'] = $selectedAvatarIcon;
        // }
        if (isset($_POST['avatarIcon']) && empty($profileData['location'])) {
            $selectedAvatarIcon = $_POST['avatarIcon'];
        
            try {

                if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
                    $row = fetchDataSingle('users_data', ['user_id' => $userId]);
                    
                    if ($row) {
                        // Update the existing profile photo entry
                        $stmt = $pdo->prepare("UPDATE users_data SET photo_loc = :photo_loc WHERE user_id = :userId AND deleted_at IS NULL");
                        $stmt->execute([
                            ':photo_loc' => $selectedAvatarIcon,
                            ':userId' => $userId
                        ]);
                    }
                }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                    $row = fetchDataSingle('profile_photo', ['user_id' => $userId, 'id' => $photo_loc]);
                    
                    if ($row) {
                        // Update the existing profile photo entry
                        $stmt = $pdo->prepare("UPDATE profile_photo SET location = :location WHERE user_id = :userId AND property_id = :property_id AND user_type = :user_type AND deleted_at IS NULL");
                        $stmt->execute([
                            ':location' => $selectedAvatarIcon,
                            ':userId' => $userId,
                            ':property_id' => $currentProperty,
                            ':user_type' => 'dealer_admins'
                        ]);
                        $photoLocId = $row['id'];
                    }
                }else {
                // Fetch existing profile photo ID
                    $row = fetchDataSingle('profile_photo', ['user_id' => $userId, 'id' => $photo_loc, 'property_id' => $currentProperty]);
                    

                    if ($row) {
                        // Update the existing profile photo entry
                        $stmt = $pdo->prepare("UPDATE profile_photo SET location = :location WHERE user_id = :userId AND property_id = :property_id AND deleted_at IS NULL");
                        $stmt->execute([
                            ':location' => $selectedAvatarIcon,
                            ':userId' => $userId,
                            ':property_id' => $currentProperty
                        ]);
                        $photoLocId = $row['id'];
                    } else {
                        // Insert new profile photo entry
                        $stmt = $pdo->prepare("INSERT INTO profile_photo (user_id, user_type, property_id, location, created_by, creator_type) VALUES (:userId, :user_type, :property_id, :location, :createdBy, :creatorType)");
                        $stmt->execute([
                            ':userId' => $userId,
                            ':user_type' => $_SESSION['user_type'],
                            ':property_id' => $currentProperty,
                            ':location' => $selectedAvatarIcon,
                            ':createdBy' => $_SESSION['userid'],
                            ':creatorType' => $creatorType
                        ]);
                        $photoLocId = $pdo->lastInsertId();
                    }
                }
        
                // Update the photo_loc field in the corresponding table
                if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
                    
                }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                    $stmt = $pdo->prepare("UPDATE dealer_admins_data SET photo_loc = :photoLocId WHERE dealer_admins_id = :userId");
                    $stmt->execute([
                        ':photoLocId' => $photoLocId,
                        ':userId' => $userId,
                    ]);
                }else if ($isMultiPropUser) {
                    $stmt = $pdo->prepare("UPDATE multi_prop_users SET photo_loc = :photoLocId WHERE user_assoc = :userId AND property_id = :propertyId AND status = 'Active'");
                    $stmt->execute([
                        ':photoLocId' => $photoLocId,
                        ':userId' => $userId,
                        ':propertyId' => $currentProperty
                    ]);
                } else {
                    $stmt = $pdo->prepare("UPDATE property_users_data SET photo_loc = :photoLocId WHERE property_user = :userId AND property_id = :propertyId");
                    $stmt->execute([
                        ':photoLocId' => $photoLocId,
                        ':userId' => $userId,
                        ':propertyId' => $currentProperty
                    ]);
                }

                $_SESSION["avatar_icon"] = $selectedAvatarIcon;
            } catch (PDOException $e) {
                $_SESSION['alert'] = [
                    "message" => "Database error: " . $e->getMessage(),
                    "type" => "danger"
                ];

                header("Location: ../../dashboard.php");
                exit();
            }
        }        

        // if (!empty($profileData['location'])) {
        //     try {
        //         if ($isMultiPropUser) {
        //             updateProfilePhotoForMultiPropUser($pdo, $userId, $currentProperty, $profileData['location']);
        //         } else {
        //             updateProfilePhoto($pdo, $userId, $creatorType, $profileData['location']);
        //         }
        //     } catch (PDOException $e) {
        //         $_SESSION['alert'] = [
        //             "message" => "Database error: " . $e->getMessage(),
        //             "type" => "danger"
        //         ];
        //         header("Location: ../../dashboard.php");
        //         exit();
        //     }
        // }

        if (!empty($profileData['location'])) {
            try {
                // Determine the correct `photo_loc` ID for this user and property
                $photoLocId = null;

                if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
                    $userAdmin = 'AdminUser';
                    // Fetch the `photo_loc` for multi_prop_users
                    $stmt = $pdo->prepare("SELECT photo_loc FROM users_data WHERE user_id = :userId");
                    $stmt->execute([
                        ':userId' => $userId
                    ]);
                    $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    $photoLocId = $result['photo_loc'] ?? null;
                }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                    $userAdmin = 'DealerAdmin';
                    $stmt = $pdo->prepare("SELECT photo_loc FROM dealer_admins_data WHERE dealer_admins_id = :userId");
                    $stmt->execute([
                        ':userId' => $userId
                    ]);
                    $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    $photoLocId = $result['photo_loc'] ?? null;
                }else if ($isMultiPropUser) {
                    $userAdmin = 'NotAdmin';
                    // Fetch the `photo_loc` for multi_prop_users
                    $stmt = $pdo->prepare("SELECT photo_loc FROM multi_prop_users WHERE user_assoc = :userId AND property_id = :propertyId AND status = 'Active'");
                    $stmt->execute([
                        ':userId' => $userId,
                        ':propertyId' => $currentProperty
                    ]);
                    $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    $photoLocId = $result['photo_loc'] ?? null;
                } else {
                    $userAdmin = 'NotAdmin';
                    // Fetch the `photo_loc` for property_users_data
                    $stmt = $pdo->prepare("SELECT photo_loc FROM property_users_data WHERE property_user = :userId AND property_id = :propertyId");
                    $stmt->execute([
                        ':userId' => $userId,
                        ':propertyId' => $currentProperty
                    ]);
                    $result = $stmt->fetch(PDO::FETCH_ASSOC);
                    $photoLocId = $result['photo_loc'] ?? null;
                }
        
                if ($userAdmin === 'AdminUser') {
                    // Update the existing `profile_photo` entry
                    $stmt = $pdo->prepare("UPDATE users_data SET photo_loc = :photo_loc WHERE id = :userid");
                    $stmt->execute([
                        ':photo_loc' => $profileData['location'],
                        ':userid' => $userId
                    ]);
                }else if ($photoLocId) {
                    // Update the existing `profile_photo` entry
                    $stmt = $pdo->prepare("UPDATE profile_photo SET location = :location WHERE id = :photoLocId");
                    $stmt->execute([
                        ':location' => $profileData['location'],
                        ':photoLocId' => $photoLocId
                    ]);
                } else {
                    // Insert a new `profile_photo` entry and update the respective table
                    $stmt = $pdo->prepare("INSERT INTO profile_photo (user_id, user_type, property_id, location, created_by, creator_type) VALUES (:userId, :user_type, :property_id, :location, :createdBy, :creatorType)");
                    $stmt->execute([
                        ':userId' => $userId,
                        ':user_type' => $_SESSION['user_type'],
                        ':property_id' => $currentProperty,
                        ':location' => $profileData['location'],
                        ':createdBy' => $_SESSION['userid'],
                        ':creatorType' => $creatorType
                    ]);
                    $photoLocId = $pdo->lastInsertId();
        
                    // Update the `photo_loc` field in the appropriate table
                    if ($isMultiPropUser) {
                        $stmt = $pdo->prepare("UPDATE multi_prop_users SET photo_loc = :photoLocId WHERE user_assoc = :userId AND property_id = :propertyId AND status = 'Active'");
                        $stmt->execute([
                            ':photoLocId' => $photoLocId,
                            ':userId' => $userId,
                            ':propertyId' => $currentProperty
                        ]);
                    } else {
                        $stmt = $pdo->prepare("UPDATE property_users_data SET photo_loc = :photoLocId WHERE property_user = :userId AND property_id = :propertyId");
                        $stmt->execute([
                            ':photoLocId' => $photoLocId,
                            ':userId' => $userId,
                            ':propertyId' => $currentProperty
                        ]);
                    }
                }
            } catch (PDOException $e) {
                $_SESSION['alert'] = [
                    "message" => "Database error: " . $e->getMessage(),
                    "type" => "danger"
                ];

                header("Location: ../../dashboard.php");
                exit();
            }
        }
        

        // Handle profile image deletion
        if (isset($_POST['delete_image']) && $_POST['delete_image'] == 1) {
            try {
                
                if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
                    deleteProfilePhotoForAdmins($userId);
                }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                    deleteProfilePhotoForDealerAdmins($userId);
                }else if ($isMultiPropUser) {
                    deleteProfilePhotoForMultiPropUser($userId, $currentProperty);
                } else {
                    deleteProfilePhotoForPropertyUser($userId, $currentProperty);
                }
                $_SESSION['alert'] = [
                    "message" => "Profile image deleted successfully.",
                    "type" => "success"
                ];
            } catch (Exception $e) {
                $_SESSION['alert'] = [
                    "message" => "An error occurred while deleting the profile image: " . $e->getMessage(),
                    "type" => "danger"
                ];
            }
            header("Location: ../../dashboard.php");
            exit();
        }

        // Handle password change
        if (isset($_POST['changePasswordSubmit'])) {
            $newPassword = $_POST['newPassword'];
            $confirmPassword = $_POST['confirmPassword'];

            if ($newPassword !== $confirmPassword) {
                $_SESSION['alert'] = [
                    "message" => "Passwords do not match.",
                    "type" => "danger"
                ];

                header("Location: ../../dashboard.php");
                exit();
            }

            $passwordPattern = '/^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]).{8,}$/';
            if (!preg_match($passwordPattern, $newPassword)) {
                $_SESSION['alert'] = [
                    "message" => "Password must be at least 8 characters, include 1 uppercase letter, 1 number, and 1 special character.",
                    "type" => "danger"
                ];

                $headerLoc = '';
                if ($_SESSION["layer"] === 'user') {
                    $headerLoc = "location: ../../command_center.php";
                }else {
                    $headerLoc = "location: ../../dashboard.php";
                }
                header($headerLoc);
                exit();
            }

            $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
            if($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
                $passwordTable = 'users';
            }elseif ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
                $passwordTable = 'dealer_admins';
            }else {
                $passwordTable = $isMultiPropUser ? 'multi_prop_users' : 'property_users';
            }

            updateTable($passwordTable, 
                ['password' => $hashedPassword], 
                'id = :id', 
                ['id' => $userId]
            );

            $_SESSION['alert'] = [
                "message" => "Password updated successfully.",
                "type" => "success"
            ];
        }

        header("Location: ../../dashboard.php");
        exit();
    } catch (Exception $e) {
        $_SESSION['alert'] = [
            "message" => "An error occurred: " . $e->getMessage(),
            "type" => "danger"
        ];
        
        $headerLoc = '';
        if ($_SESSION["layer"] === 'user') {
            $headerLoc = "location: ../../command_center.php";
        }else {
            $headerLoc = "location: ../../dashboard.php";
        }
        header($headerLoc);
        exit();
    }
}

