<?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 {
        $fullname = strip_tags($_POST['fullname']);
        $email = strip_tags($_POST['email']);
        $username = strip_tags($_POST['username']);
        $pass = strip_tags($_POST['password']);
        $password2 = strip_tags($_POST['password2']);
        $access_level = strip_tags($_POST['access_level']);

        // Check if passwords match
        if ($pass !== $password2) {
            $_SESSION['msg'] = "failed";
            $_SESSION['error_message'] = "Passwords do not match!";
            redirect('add_admin.php');
            exit;
        }

        // Encrypt password
        $password = md5(md5($salt . md5($pass)) . $salt);

        // Check if email already exists
        $STH = $DBH->prepare("SELECT count(*) FROM tbl_admin WHERE email = ?");
        $result = $STH->execute(array($email));
        $count_email = $STH->fetchColumn();

        // Check if username already exists
        $STH = $DBH->prepare("SELECT count(*) FROM tbl_admin WHERE username = ?");
        $result = $STH->execute(array($username));
        $count_username = $STH->fetchColumn();

        // Check if email or username already exists
        if ($count_email > 0) {
            $_SESSION['msg'] = "email";
            redirect('add_admin.php');
            exit;
        } elseif ($count_username > 0) {
            $_SESSION['msg'] = "username";
            redirect('add_admin.php');
            exit;
        }

        // Handle photo upload
        $photo = "default_admin.jpg"; // default 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");
            }
        }

        // Generate registration date
        $registration_date = date("D d M Y");

        // Generate random hash
        $hash = md5(rand(0, 1000));

        // Get the last admin ID and increment
        $STH = $DBH->query("SELECT MAX(id) FROM tbl_admin");
        $last_id = $STH->fetchColumn();
        $new_id = $last_id + 1;

        // Insert admin into database
        sql(
            $DBH,
            "INSERT INTO tbl_admin (id, fullname, email, username, password, photo, registration_date, access_level, hash, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            array($new_id, $fullname, $email, $username, $password, $photo, $registration_date, $access_level, $hash, "Active")
        );

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