<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');

if (isset($_POST['submit'])) {
    try {
        $admin_id = (int)$_POST['admin_id'];
        $fullname = strip_tags($_POST['fullname']);
        $email = strip_tags($_POST['email']);
        $username = strip_tags($_POST['username']);
        $password = isset($_POST['password']) ? strip_tags($_POST['password']) : '';
        $password2 = isset($_POST['password2']) ? strip_tags($_POST['password2']) : '';
        $access_level = strip_tags($_POST['access_level']);
        $status = strip_tags($_POST['status']);

        // Check if passwords are provided and match
        if (!empty($password)) {
            if ($password !== $password2) {
                $_SESSION['msg'] = "password_mismatch";
                header("Location: edit_admin.php?admin_id=".$admin_id);
                exit;
            }
            $password = md5(md5($salt . md5($password)) . $salt);
        }

        // Check if email already exists for another admin
        $STH = $DBH->prepare("SELECT id FROM tbl_admin WHERE email = ? AND id != ?");
        $STH->execute(array($email, $admin_id));
        if ($STH->fetchColumn()) {
            $_SESSION['msg'] = "email_exists";
            header("Location: edit_admin.php?admin_id=".$admin_id);
            exit;
        }

        // Check if username already exists for another admin
        $STH = $DBH->prepare("SELECT id FROM tbl_admin WHERE username = ? AND id != ?");
        $STH->execute(array($username, $admin_id));
        if ($STH->fetchColumn()) {
            $_SESSION['msg'] = "username_exists";
            header("Location: edit_admin.php?admin_id=".$admin_id);
            exit;
        }

        // Handle photo upload
        $photo = '';
        if (!empty($_FILES['photo']['name'])) {
            $photo = $_FILES['photo']['name'];
            $photo_temp = $_FILES['photo']['tmp_name'];
            $upload_dir = "profile_pic/";
            
            // Create directory if it doesn't exist
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Move uploaded file
            if (!move_uploaded_file($photo_temp, $upload_dir . $photo)) {
                throw new Exception("Failed to upload photo");
            }
        }

        // Prepare update query
        $update_fields = array(
            'fullname' => $fullname,
            'email' => $email,
            'username' => $username,
            'access_level' => $access_level,
            'status' => $status
        );

        // Add password if changed
        if (!empty($password)) {
            $update_fields['password'] = $password;
        }

        // Add photo if changed
        if (!empty($photo)) {
            $update_fields['photo'] = $photo;
        }

        // Build the SQL query
        $set_clause = implode(', ', array_map(function($field) {
            return "$field = ?";
        }, array_keys($update_fields)));

        $values = array_values($update_fields);
        $values[] = $admin_id;

        // Update admin in database
        $query = "UPDATE tbl_admin SET $set_clause WHERE id = ?";
        $STH = $DBH->prepare($query);
        $STH->execute($values);

        $_SESSION['msg'] = "updated";
        header("Location: edit_admin.php?admin_id=".$admin_id);
        exit;
    } catch (PDOException $e) {
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        $_SESSION['msg'] = "failed";
        $_SESSION['error_message'] = "Database error: " . $e->getMessage();
        header("Location: edit_admin.php?admin_id=".$admin_id);
    } catch (Exception $e) {
        $_SESSION['msg'] = "failed";
        $_SESSION['error_message'] = $e->getMessage();
        header("Location: edit_admin.php?admin_id=".$admin_id);
    }
} else {
    $_SESSION['msg'] = "failed";
    $_SESSION['error_message'] = "Invalid request method";
    header("Location: list_admin.php");
}
?>