CREATE TABLE IF NOT EXISTS `settings` (
    `setting_key` VARCHAR(255) NOT NULL,
    `setting_value` VARCHAR(255),
    PRIMARY KEY (`setting_key`)
);

CREATE TABLE IF NOT EXISTS `users` (
    `user_id` INT NOT NULL AUTO_INCREMENT,
    `display_name` VARCHAR(255),
    `email` VARCHAR(255) NOT NULL UNIQUE,
    `password` VARCHAR(255) NOT NULL,
    `salt` VARCHAR(255) NOT NULL,
    `is_admin` BOOLEAN,
    PRIMARY KEY (`user_id`)
);

CREATE TABLE IF NOT EXISTS `user_sessions` (
    `session_id` VARCHAR(255) NOT NULL,
    `salt` VARCHAR(255) NOT NULL,
    `user_id` INT NOT NULL,
    `expiry` DATETIME NOT NULL,
    PRIMARY KEY (`session_id`),
    FOREIGN KEY (`user_id`) REFERENCES `users`(`user_id`)
);

CREATE TABLE IF NOT EXISTS `locations` (
    `location_id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(255) NOT NULL,
    `logo` BLOB,
    PRIMARY KEY (`location_id`)
);

CREATE TABLE IF NOT EXISTS `permissions` (
    `user_id` INT NOT NULL,
    `location_id` INT NOT NULL,
    `is_owner` BOOLEAN,
    PRIMARY KEY (`user_id`, `location_id`),
    FOREIGN KEY (`user_id`) REFERENCES `users`(`user_id`),
    FOREIGN KEY (`location_id`) REFERENCES `locations`(`location_id`)
);

CREATE TABLE IF NOT EXISTS `visits` (
    `visit_id` VARCHAR(255) NOT NULL,
    `location_id` INT NOT NULL,
    `arrival` DATETIME NOT NULL,
    `departure` DATETIME NOT NULL,
    PRIMARY KEY (`visit_id`),
    FOREIGN KEY (`location_id`) REFERENCES `locations`(`location_id`)
);

CREATE TABLE IF NOT EXISTS `visitors` (
    `visitor_id` INT NOT NULL AUTO_INCREMENT,
    `visit_id` VARCHAR(255) NOT NULL,
    `first_name` VARCHAR(255) NOT NULL,
    `last_name` VARCHAR(255) NOT NULL,
    `address1` VARCHAR(255),
    `address2` VARCHAR(255),
    `zip` VARCHAR(255),
    `city` VARCHAR(255),
    `state` VARCHAR(255),
    `country` VARCHAR(255),
    `phone` VARCHAR(255),
    `email` VARCHAR(255),
    PRIMARY KEY (`visitor_id`),
    FOREIGN KEY (`visit_id`) REFERENCES `visits`(`visit_id`)
);

CREATE TABLE IF NOT EXISTS `visit_sessions` (
    `session_id` VARCHAR(255) NOT NULL,
    `salt` VARCHAR(255) NOT NULL,
    `visit_id` VARCHAR(255) NOT NULL,
    `expiry` DATETIME,
    PRIMARY KEY (`session_id`),
    FOREIGN KEY (`visit_id`) REFERENCES `visits`(`visit_id`)
);