based on this info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Dec 01, 2024 at 02:13 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `u406552082_kaakalia`
--

-- --------------------------------------------------------

--
-- Table structure for table `ads`
--

CREATE TABLE `ads` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `ad_type` enum('Post','Story') NOT NULL,
  `related_id` int(11) NOT NULL,
  `budget` decimal(10,2) NOT NULL,
  `total_spent` decimal(10,2) DEFAULT 0.00,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  `status` enum('Active','Paused','Completed') DEFAULT 'Active',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `ad_spend_logs`
--

CREATE TABLE `ad_spend_logs` (
  `id` int(11) NOT NULL,
  `ad_id` int(11) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `spend_date` datetime DEFAULT current_timestamp(),
  `description` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `contact` varchar(50) DEFAULT NULL,
  `delivery_address` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`id`, `name`, `contact`, `delivery_address`) VALUES
(1, 'Order_3121', '012345689', 'Qena'),
(2, 'order_3212', '51648963', 'Luxor'),
(3, 'Order_323', '01119235049', 'Qena, Egypt'),
(4, 'Order_3231', '0155648963', 'Luxor'),
(5, 'Order_3548464852', '0110215489', 'Qena'),
(6, 'Order_mahmoud', '50495049', 'Qena'),
(7, 'Ahmed', '01119235049', 'Assuit'),
(8, 'Mahmoud Tawfik', '01119235049', 'Qena, Center Qena'),
(9, 'Ahmed', '0101549463', 'Luxor'),
(10, 'Yossef', '0154949463', 'Aswan'),
(11, 'Mona', '0154984315', 'Qena'),
(12, 'Order_132323', '0119548463', 'CXA'),
(13, 'Mostafa', '154946123', 'Assuit'),
(14, 'Order_66960907', '+96566960907', 'kuwait'),
(15, 'Order_84569845', '+96584569845', 'Kuwait'),
(16, 'Order_84656222', '+96584656222', 'Mashrif'),
(17, 'Order_84549651', '+96584549651', 'Luxor'),
(18, 'Order_94531154', '+96594531154', 'Qena'),
(19, 'Order_56123548', '+96556123548', 'luxor'),
(20, 'Order_84562148', '+96584562148', NULL),
(21, 'Order_54632154', '+96554632154', 'Luxor'),
(22, 'Order_84561254', '+96584561254', 'Qena');

-- --------------------------------------------------------

--
-- Table structure for table `deals`
--

CREATE TABLE `deals` (
  `id` int(11) NOT NULL,
  `influencer_id` int(11) NOT NULL,
  `deal_type` enum('Sponsorship','Booth','Other') NOT NULL,
  `description` text DEFAULT NULL,
  `compensation` decimal(10,2) DEFAULT 0.00,
  `status` enum('Pending','Confirmed','Completed','Cancelled') DEFAULT 'Pending',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `drivers`
--

CREATE TABLE `drivers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `number` varchar(15) NOT NULL,
  `is_star` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `drivers`
--

INSERT INTO `drivers` (`id`, `name`, `number`, `is_star`) VALUES
(1, 'Fox ØªÙˆØµÙŠÙ„', '+965 9944 6116', 0),
(2, 'Perfect M ØªÙˆØµÙŠÙ„ 3kd', '+965 555 72147', 0),
(3, 'ØªÙˆØµÙŠÙ„ Ù¥', '+965 505 02769', 0),
(4, 'Shipping Company ØªÙˆØµÙŠÙ„ Delivery', '+965 9940 7010', 0),
(5, 'ØªÙˆØµÙŠÙ„ÙƒÙ… ØªÙˆØµÙŠÙ„ Delivery', '+965 517 66244', 0),
(6, 'ØªÙˆØµÙŠÙ„ Ø§Ù„ÙƒÙˆÙŠØª Ù¢', '+965 557 25712', 0),
(7, 'ØªÙˆØµÙŠÙ„ Ø§Ù„ÙƒÙˆÙŠØª 2.5kd', '+965 6049 4960', 0),
(8, 'ÙƒÙ„Ø§Ø³Ùƒ ØªÙˆØµÙŠÙ„', '+965 6969 1459', 0),
(9, 'Ø³Ø§ÙŠÙ‚ On Call5 Delivery Freelance', '+965 6698 8976', 1),
(10, 'Ø³Ø§ÙŠÙ‚ On Call 3 Delivery Freelance', '+965 555 86442', 0),
(11, 'Ø³Ø§ÙŠÙ‚ On Call 2 Delivery Freelance', '+965 555 12101', 0),
(12, 'Delivery ØªÙˆØµÙŠÙ„', '+965 9851 8182', 0),
(13, 'Kumar Driver', '+965 6673 8688', 1),
(14, 'Pawan Driver', '+965 9733 1565', 0),
(15, 'ØªÙˆØµÙŠÙ„ - ØµÙ„Ø§Ø­', '+965 6576 2337', 0);

-- --------------------------------------------------------

--
-- Table structure for table `influencers`
--

CREATE TABLE `influencers` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `contact_number` varchar(50) NOT NULL,
  `contact_info` varchar(255) NOT NULL,
  `address` text NOT NULL,
  `social_media` varchar(255) DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `delivery_datetime` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `influencers`
--

INSERT INTO `influencers` (`id`, `name`, `contact_number`, `contact_info`, `address`, `social_media`, `notes`, `delivery_datetime`, `created_at`, `updated_at`) VALUES
(2, 'Ahmed', '945846126', 'mahmoudtawfikh@gmail.com', 'Assuit', 'instagram', 'kilo shobara \r\nhalf kilo monkey bread', '2024-11-19 12:00:00', '2024-11-18 09:15:10', '2024-11-18 09:15:10');

-- --------------------------------------------------------

--
-- Table structure for table `interactions`
--

CREATE TABLE `interactions` (
  `id` int(11) NOT NULL,
  `influencer_id` int(11) NOT NULL,
  `interaction_date` datetime NOT NULL,
  `method` enum('Email','Phone','In-Person','Social Media','Other') NOT NULL,
  `notes` text DEFAULT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `notifications`
--

CREATE TABLE `notifications` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `type` enum('order','post','plan','note','ad') NOT NULL,
  `message` varchar(255) NOT NULL,
  `link` varchar(255) NOT NULL,
  `created_at` datetime DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `status` enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
  `priority` enum('Normal','Important','Quick') DEFAULT 'Normal',
  `order_date` datetime DEFAULT current_timestamp(),
  `delivery_datetime` datetime DEFAULT NULL,
  `delivery_date` date DEFAULT NULL,
  `delivery_fee` decimal(10,2) NOT NULL DEFAULT 0.00,
  `free_shipping` tinyint(1) NOT NULL DEFAULT 0,
  `is_paid` tinyint(1) NOT NULL DEFAULT 0,
  `pickup` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`id`, `customer_id`, `status`, `priority`, `order_date`, `delivery_datetime`, `delivery_date`, `delivery_fee`, `free_shipping`, `is_paid`, `pickup`) VALUES
(4, 4, 'Delivered', 'Normal', '2024-11-09 14:48:25', '2024-11-16 08:50:00', NULL, 0.00, 0, 0, 0),
(5, 5, 'Delivered', 'Normal', '2024-11-09 18:28:01', '2024-11-10 09:00:00', NULL, 0.00, 0, 0, 0),
(6, 6, 'Delivered', 'Important', '2024-11-12 09:49:43', '2024-11-13 16:00:00', NULL, 0.00, 0, 0, 0),
(8, 8, 'Delivered', 'Important', '2024-11-12 17:57:16', '2024-11-13 12:00:00', NULL, 0.00, 0, 0, 0),
(9, 9, 'Delivered', 'Important', '2024-11-12 18:16:47', '2024-11-13 15:00:00', NULL, 1.00, 0, 0, 0),
(10, 10, 'Pending', 'Quick', '2024-11-12 18:50:43', '2024-11-13 18:00:00', NULL, 0.00, 0, 0, 0),
(12, 12, 'Pending', 'Quick', '2024-11-13 12:25:55', NULL, NULL, 0.00, 1, 1, 0),
(17, 17, 'Pending', 'Important', '2024-11-14 22:49:41', '2024-11-16 12:00:00', NULL, 1.00, 0, 1, 0),
(18, 18, 'Pending', 'Important', '2024-11-14 23:03:27', '2024-11-16 14:00:00', NULL, 1.00, 0, 1, 0),
(19, 19, 'Delivered', 'Normal', '2024-11-15 12:18:46', '2024-11-16 14:00:00', NULL, 1.00, 0, 1, 0),
(20, 20, 'In Progress', 'Important', '2024-11-16 21:28:35', '2024-11-17 11:00:00', NULL, 0.00, 0, 0, 0),
(21, 21, 'Pending', 'Important', '2024-11-16 21:52:46', '2024-11-18 12:00:00', NULL, 2.00, 0, 0, 0),
(22, 22, 'Pending', 'Important', '2024-11-17 22:21:09', '2024-11-21 12:00:00', NULL, 0.00, 0, 0, 1);

-- --------------------------------------------------------

--
-- Table structure for table `order_items`
--

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL DEFAULT 1,
  `packaging_preferences` varchar(255) DEFAULT NULL,
  `discount_percentage` decimal(5,2) DEFAULT 0.00,
  `discount_reason` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `order_items`
--

INSERT INTO `order_items` (`id`, `order_id`, `product_id`, `quantity`, `packaging_preferences`, `discount_percentage`, `discount_reason`) VALUES
(5, 4, 8, 1, 'This Order type one Mahmoud Tawfik', 0.00, '<br /><b>Deprecated</b>:  htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in <b>/home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/edit_order.php</b> on line <b>692</b><br />'),
(6, 5, 2, 1, '0', 20.00, 'Ø®ØµÙ… Ù…Ø´Ø±Ù'),
(7, 4, 6, 2, 'Add Card on it', 30.00, ''),
(8, 6, 6, 1, '0', 0.00, NULL),
(10, 8, 2, 2, 'add Card on box, this card is &quot;Mahmoud Tawfik&quot;', 30.00, 'Ø®ØµÙ… Ø§Ù„Ù…Ø´Ø±Ù'),
(11, 9, 7, 1, 'type on \"Mahmoud\"', 0.00, '<br /><b>Deprecated</b>:  htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in <b>/home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/edit_order.php</b> on line <b>749</b><br />'),
(12, 10, 3, 1, 'Type: Mahmoud Tawfik', 0.00, NULL),
(14, 12, 8, 5, '', 0.00, ''),
(19, 12, 8, 1, '0', 0.00, '0'),
(20, 17, 6, 1, '', 30.00, 'Ø®ØµÙ… Ù…Ø´Ø±Ù'),
(21, 17, 5, 2, '0', 25.00, '0'),
(22, 18, 7, 1, 'Add Card, Mahmoud', 30.00, 'Ø®ØµÙ… Ø§Ù„Ù…Ø´Ø±Ù'),
(23, 18, 1, 1, 'Add Card, Ahmed', 30.00, 'Ø®ØµÙ… Ø§Ù„Ù…Ø´Ø±Ù'),
(24, 18, 5, 1, 'Add Card, ASC', 30.00, '0'),
(25, 19, 2, 5, 'Add Card :Mahmoud Tawfik:', 30.00, 'Ø®ØµÙ… Ù…Ø´Ø±Ù'),
(26, 20, 7, 1, 'Add New Card \"Mahmoud Tawfik\"', 30.00, 'Ø®ØµÙ… Ù…Ø´Ø±Ù'),
(27, 21, 9, 1, '', 0.00, ''),
(28, 22, 7, 1, 'Wahab', 0.00, ''),
(29, 22, 6, 1, 'add new order', 0.00, '');

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `size` varchar(50) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL,
  `category` varchar(50) DEFAULT NULL,
  `thumbnail` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `size`, `price`, `category`, `thumbnail`) VALUES
(1, 'Shabora', 'Half Kilo', 6.00, 'Cakes', NULL),
(2, 'Shabora', 'One Kilo', 8.00, 'Cakes', NULL),
(3, 'Shabora', 'Small Basket', 8.00, 'Cakes', NULL),
(4, 'Shabora', 'Large Basket', 10.00, 'Cakes', NULL),
(5, 'Shabora', 'Presentation Plate (Ivory)', 14.00, 'Cakes', NULL),
(6, 'Mahalbiya Crunch', '12 Pieces', 12.00, 'Desserts', NULL),
(7, 'Monkey Bread', 'Large', 12.00, 'Breads', NULL),
(8, 'Monkey Bread Mini', '12 Pieces', 6.00, 'Breads', NULL),
(9, 'Monkey Bread Mini', '9 Pieces', 9.00, 'Breads', NULL),
(11, 'Monkey Bread', 'Presentation Plate', 16.00, 'Breads', NULL);

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `email` varchar(100) DEFAULT NULL,
  `password` varchar(255) NOT NULL,
  `role` enum('admin','staff') NOT NULL,
  `profile_image` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `email`, `password`, `role`, `profile_image`) VALUES
(1, 'kaakalia', 'user@example.com', '$2y$10$tEdSPRwL8WTXljuAxNh.m.af/8sHd/ouDB21Bgs1bC7GkbRq/h0D6', 'admin', 'uploads/profile_images/profile_kaakalia_1731274341.png'),
(2, 'mahmoudtawfik', 'mahmoudtawfikh@gmail.com', '$2y$10$0yxg1R.kfbVV7GL4G9/Q3u5PK.cvv8p29R3ggkfUMC2.aRiAXb2cO', 'admin', 'uploads/profile_images/profile_mahmoudtawfik_1731274427.jpg'),
(3, 'haya', 'haya@gmail.com', '$2y$10$ri1wzOhcmT2YVGkoPYjwu.3fY8xayakQEWHjTaAFGkPfDwJ50PIh6', 'admin', 'uploads/profile_images/profile_haya_1731304053.jpg');

-- --------------------------------------------------------

--
-- Table structure for table `workspace_notes`
--

CREATE TABLE `workspace_notes` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `workspace_notes`
--

INSERT INTO `workspace_notes` (`id`, `user_id`, `title`, `content`, `created_at`, `updated_at`) VALUES
(2, 2, 'This important notes', 'HaloHaloHaloHaloHaloHaloHaloHaloHaloHalo', '2024-11-11 09:37:10', '2024-11-11 09:37:10');

-- --------------------------------------------------------

--
-- Table structure for table `workspace_plans`
--

CREATE TABLE `workspace_plans` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `audio_path` varchar(255) DEFAULT NULL,
  `due_date` datetime DEFAULT NULL,
  `status` enum('Not Started','In Progress','Completed') DEFAULT 'Not Started',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `priority` enum('Normal','Important','Critical') NOT NULL DEFAULT 'Normal'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `workspace_posts`
--

CREATE TABLE `workspace_posts` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `platform` enum('Instagram','Facebook','Twitter','Other') NOT NULL,
  `content` text NOT NULL,
  `media_url` varchar(255) DEFAULT NULL,
  `scheduled_datetime` datetime DEFAULT NULL,
  `status` enum('Scheduled','Posted','Failed') DEFAULT 'Scheduled',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `type` enum('Post','Story') DEFAULT 'Post'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `workspace_posts`
--

INSERT INTO `workspace_posts` (`id`, `user_id`, `platform`, `content`, `media_url`, `scheduled_datetime`, `status`, `created_at`, `updated_at`, `type`) VALUES
(2, 1, 'Instagram', 'Hello', NULL, '2024-11-11 01:19:00', 'Scheduled', '2024-11-10 11:16:10', '2024-11-10 11:16:10', 'Post');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `ads`
--
ALTER TABLE `ads`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `related_id` (`related_id`);

--
-- Indexes for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `ad_id` (`ad_id`);

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `deals`
--
ALTER TABLE `deals`
  ADD PRIMARY KEY (`id`),
  ADD KEY `influencer_id` (`influencer_id`);

--
-- Indexes for table `drivers`
--
ALTER TABLE `drivers`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `influencers`
--
ALTER TABLE `influencers`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `interactions`
--
ALTER TABLE `interactions`
  ADD PRIMARY KEY (`id`),
  ADD KEY `influencer_id` (`influencer_id`);

--
-- Indexes for table `notifications`
--
ALTER TABLE `notifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `created_at` (`created_at`);

--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `customer_id` (`customer_id`),
  ADD KEY `idx_orders_customer_id` (`customer_id`);

--
-- Indexes for table `order_items`
--
ALTER TABLE `order_items`
  ADD PRIMARY KEY (`id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `product_id` (`product_id`),
  ADD KEY `idx_order_items_order_id` (`order_id`),
  ADD KEY `idx_order_items_product_id` (`product_id`);

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `ads`
--
ALTER TABLE `ads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;

--
-- AUTO_INCREMENT for table `deals`
--
ALTER TABLE `deals`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `drivers`
--
ALTER TABLE `drivers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;

--
-- AUTO_INCREMENT for table `influencers`
--
ALTER TABLE `influencers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `interactions`
--
ALTER TABLE `interactions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `notifications`
--
ALTER TABLE `notifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;

--
-- AUTO_INCREMENT for table `order_items`
--
ALTER TABLE `order_items`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30;

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;

--
-- AUTO_INCREMENT for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `ads`
--
ALTER TABLE `ads`
  ADD CONSTRAINT `fk_ads_related_id` FOREIGN KEY (`related_id`) REFERENCES `workspace_posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_ads_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  ADD CONSTRAINT `fk_ad_spend_logs_ad_id` FOREIGN KEY (`ad_id`) REFERENCES `ads` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `deals`
--
ALTER TABLE `deals`
  ADD CONSTRAINT `deals_ibfk_1` FOREIGN KEY (`influencer_id`) REFERENCES `influencers` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `interactions`
--
ALTER TABLE `interactions`
  ADD CONSTRAINT `interactions_ibfk_1` FOREIGN KEY (`influencer_id`) REFERENCES `influencers` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `notifications`
--
ALTER TABLE `notifications`
  ADD CONSTRAINT `notifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
  ADD CONSTRAINT `fk_orders_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `order_items`
--
ALTER TABLE `order_items`
  ADD CONSTRAINT `fk_order_items_order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_order_items_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  ADD CONSTRAINT `fk_workspace_notes_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  ADD CONSTRAINT `fk_workspace_plans_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  ADD CONSTRAINT `fk_workspace_posts_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) and based on this add order (<?php
// public/orders/add_order.php

// Enable comprehensive error reporting for debugging purposes
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start output buffering to prevent "headers already sent" errors
ob_start();

// Include authentication, database connection, and functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Ensure sanitize_input() is defined

// Verify that sanitize_input() exists
if (!function_exists('sanitize_input')) {
    die("Error: sanitize_input() function is not defined.");
}

// Initialize variables
$success = '';
$error = '';
$customer_name = '';
$full_contact = '';

// Define an array of countries with their dialing codes
$countries = [
    "Afghanistan" => "+93",
    "Albania" => "+355",
    "Algeria" => "+213",
    "Andorra" => "+376",
    "Angola" => "+244",
    "Antigua and Barbuda" => "+1-268",
    "Argentina" => "+54",
    "Armenia" => "+374",
    "Australia" => "+61",
    "Austria" => "+43",
    "Azerbaijan" => "+994",
    "Bahamas" => "+1-242",
    "Bahrain" => "+973",
    "Bangladesh" => "+880",
    "Barbados" => "+1-246",
    "Belarus" => "+375",
    "Belgium" => "+32",
    "Belize" => "+501",
    "Benin" => "+229",
    "Bhutan" => "+975",
    "Bolivia" => "+591",
    "Bosnia and Herzegovina" => "+387",
    "Botswana" => "+267",
    "Brazil" => "+55",
    "Brunei" => "+673",
    "Bulgaria" => "+359",
    "Burkina Faso" => "+226",
    "Burundi" => "+257",
    // ... (Add all other countries as needed)
    "Kuwait" => "+965",
    // Continue adding countries up to the desired list
];

// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);

if (!$products_result) {
    die("Error fetching products: " . $conn->error);
}

// Fetch all products into an associative array
$products = $products_result->fetch_all(MYSQLI_ASSOC);

// Initialize priority with default value
$priority = 'Normal';

// Set $selected_country to POST value or default to '+965'
$selected_country = sanitize_input($_POST['country'] ?? '+965');

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate input
    $contact_input = sanitize_input($_POST['contact'] ?? '');
    $delivery_address = sanitize_input($_POST['delivery_address'] ?? '');
    $customer_name_input = sanitize_input($_POST['customer_name'] ?? '');

    // Determine if the customer will pick up the order
    $pickup = isset($_POST['pickup']) ? 1 : 0;

    // Extract digits from contact number
    $contact_digits = preg_replace('/\D/', '', $contact_input);
    if (empty($contact_digits)) {
        $error = "A valid contact number is required.";
    } else {
        // Full contact number with country code
        $full_contact = $selected_country . $contact_digits;

        // Generate customer name or use provided name
        if (!empty($customer_name_input)) {
            $customer_name = $customer_name_input;
        } else {
            $customer_name = $pickup ? 'Pickup_Order_' . $contact_digits : 'Order_' . $contact_digits;
        }
    }

    // Set priority
    $priority = sanitize_input($_POST['priority'] ?? 'Normal');

    // Handle free shipping and delivery fee based on pickup status
    if (!$pickup) {
        $free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
        $delivery_fee = $free_shipping ? 0.00 : (isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00);
    } else {
        // For pickup orders, set delivery fee and free shipping to defaults
        $free_shipping = 0;
        $delivery_fee = 0.00;
    }

    // Validate priority
    $valid_priorities = ['Normal', 'Important', 'Quick'];
    if (!in_array($priority, $valid_priorities)) {
        $priority = 'Normal';
    }

    // Handle multiple products
    $product_ids = $_POST['product_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $packaging_preferences = $_POST['packaging_preferences'] ?? [];
    $apply_discount = $_POST['apply_discount'] ?? [];
    $discount_percentages = $_POST['discount_percentage'] ?? [];
    $discount_reasons = $_POST['discount_reason'] ?? [];

    // Basic validation
    if (empty($customer_name)) {
        $error = "Customer name generation failed.";
    } elseif (empty($contact_input)) {
        $error = "Contact number is required.";
    } elseif (empty($product_ids) || !is_array($product_ids) || count($product_ids) == 0) {
        $error = "At least one product must be selected.";
    } else {
        // Validate each product entry
        foreach ($product_ids as $index => $pid) {
            if (empty($pid)) {
                $error = "Product selection is required for all items.";
                break;
            }
            if (!isset($quantities[$index]) || intval($quantities[$index]) <= 0) {
                $error = "Quantity must be at least 1 for all items.";
                break;
            }
            // If discount is applied, validate discount fields
            if (isset($apply_discount[$index])) {
                $discount = trim($discount_percentages[$index]);
                $reason = trim($discount_reasons[$index]);
                if ($discount === '') {
                    $error = "Discount percentage is required if discount is applied.";
                    break;
                }
                if (!is_numeric($discount) || floatval($discount) < 0 || floatval($discount) > 100) {
                    $error = "Invalid discount percentage for product. It should be between 0 and 100.";
                    break;
                }
                if (empty($reason)) {
                    $error = "Discount reason is required if discount is applied.";
                    break;
                }
            }
        }

        // Validate delivery_datetime
        $delivery_datetime_input = $_POST['delivery_datetime'] ?? '';
        if (!empty($delivery_datetime_input)) {
            // Convert from 'Y-m-d\TH:i' to 'Y-m-d H:i:s'
            $delivery_datetime = sanitize_input(str_replace('T', ' ', $delivery_datetime_input) . ':00');
            if (!preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/", $delivery_datetime)) {
                $error = "Invalid delivery date and time format.";
            } elseif (strtotime($delivery_datetime) < strtotime(date('Y-m-d H:i:s'))) {
                $error = "Delivery date and time cannot be in the past.";
            }
        } else {
            $delivery_datetime = null;
        }

        /**
         * FIX: Adjust the validation condition to exclude cases where pickup is selected.
         * Previously, the delivery_fee was being validated even when pickup was selected,
         * leading to the error message when the delivery_fee field was disabled and not submitted.
         */
        if (!$free_shipping && !$pickup) {
            if (!isset($_POST['delivery_fee']) || !is_numeric($_POST['delivery_fee']) || floatval($_POST['delivery_fee']) < 0) {
                $error = "Valid delivery fee is required.";
            }
        }

        // Validate delivery_fee if not free shipping and not pickup
        if (!$free_shipping && !$pickup) {
            if (!isset($_POST['delivery_fee']) || !is_numeric($_POST['delivery_fee']) || floatval($_POST['delivery_fee']) < 0) {
                // This condition is now handled above, so you might consider removing it to avoid duplication
                // $error = "Valid delivery fee is required.";
            }
        }

        // If no error, proceed to insert data
        if (empty($error)) {
            // Validate delivery_fee one more time to ensure it's correctly set
            if (!$free_shipping && !$pickup && !is_numeric($delivery_fee)) {
                $error = "Valid delivery fee is required.";
            } elseif (!$free_shipping && !$pickup && floatval($delivery_fee) < 0) {
                $error = "Delivery fee cannot be negative.";
            }
        }

        if (empty($error)) {
            // Additional validation for delivery_datetime
            if ($delivery_datetime === null) {
                $delivery_datetime = null; // Explicitly set to null
            }

            // Continue with order insertion
            if (empty($error)) {
                // Start transaction
                $conn->begin_transaction();

                try {
                    if (!$pickup) {
                        // Insert into customers table using prepared statement
                        if (!empty($delivery_address)) {
                            $stmt = $conn->prepare("INSERT INTO customers (name, contact, delivery_address) VALUES (?, ?, ?)");
                            if (!$stmt) {
                                throw new Exception("Prepare statement failed: " . $conn->error);
                            }
                            $stmt->bind_param("sss", $customer_name, $full_contact, $delivery_address);
                        } else {
                            $stmt = $conn->prepare("INSERT INTO customers (name, contact) VALUES (?, ?)");
                            if (!$stmt) {
                                throw new Exception("Prepare statement failed: " . $conn->error);
                            }
                            $stmt->bind_param("ss", $customer_name, $full_contact);
                        }

                        if (!$stmt->execute()) {
                            throw new Exception("Execute failed: " . $stmt->error);
                        }
                        $customer_id = $stmt->insert_id;
                        $stmt->close();
                    } else {
                        // Insert into customers table without delivery_address
                        $stmt = $conn->prepare("INSERT INTO customers (name, contact) VALUES (?, ?)");
                        if (!$stmt) {
                            throw new Exception("Prepare statement failed: " . $conn->error);
                        }
                        $stmt->bind_param("ss", $customer_name, $full_contact);
                        if (!$stmt->execute()) {
                            throw new Exception("Execute failed: " . $stmt->error);
                        }
                        $customer_id = $stmt->insert_id;
                        $stmt->close();
                    }

                    // Insert into orders table using prepared statement
                    $status = 'Pending'; // Default status

                    $stmt = $conn->prepare("INSERT INTO orders (customer_id, status, priority, delivery_datetime, delivery_fee, free_shipping, pickup) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    if (!$stmt) {
                        throw new Exception("Prepare statement failed: " . $conn->error);
                    }

                    // Bind parameters
                    if ($delivery_datetime === null) {
                        // When delivery_datetime is null
                        $stmt->bind_param(
                            "isssiii",
                            $customer_id,
                            $status,
                            $priority,
                            $delivery_datetime,
                            $delivery_fee,
                            $free_shipping,
                            $pickup
                        );
                        // No need to use send_long_data for setting NULL, mysqli will handle it
                    } else {
                        $stmt->bind_param(
                            "isssiii",
                            $customer_id,
                            $status,
                            $priority,
                            $delivery_datetime,
                            $delivery_fee,
                            $free_shipping,
                            $pickup
                        );
                    }

                    if (!$stmt->execute()) {
                        throw new Exception("Execute failed: " . $stmt->error);
                    }
                    $order_id = $stmt->insert_id;
                    $stmt->close();

                    // Insert products into order_items table
                    $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason) VALUES (?, ?, ?, ?, ?, ?)");
                    if (!$stmt) {
                        throw new Exception("Prepare statement failed: " . $conn->error);
                    }

                    // Loop through each product
                    foreach ($product_ids as $index => $pid) {
                        $pid = intval($pid);
                        $qty = intval($quantities[$index]);
                        $pack_pref = sanitize_input($packaging_preferences[$index] ?? '');

                        // Handle discount
                        $discount_percent = 0.00;
                        $discount_rs = '';
                        if (isset($apply_discount[$index])) {
                            $discount_percent = floatval(trim($discount_percentages[$index]));
                            $discount_rs = sanitize_input($discount_reasons[$index]);
                        }

                        $stmt->bind_param("iiisds", $order_id, $pid, $qty, $pack_pref, $discount_percent, $discount_rs);
                        if (!$stmt->execute()) {
                            throw new Exception("Execute failed: " . $stmt->error);
                        }
                    }

                    $stmt->close();

                    // Commit transaction
                    $conn->commit();

                    // Redirect to view_orders.php after successful addition
                    header("Location: view_orders.php?success=1");
                    exit();
                } catch (Exception $e) {
                    // Rollback transaction
                    $conn->rollback();
                    $error = "Error adding order: " . $e->getMessage();
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add New Order - Kaak Alia Management System</title>
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Custom Styles -->
    <style>
        /* Custom scrollbar for better UX */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f5f9; /* Tailwind's gray-100 */
        }

        ::-webkit-scrollbar-thumb {
            background: #20B2AA; /* Teal-500 */
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #0d9488; /* Teal-600 */
        }

        /* Responsive Table */
        @media (max-width: 768px) {
            table {
                min-width: 600px;
            }
        }

        /* Tooltip styles */
        .tooltip {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 250px;
            background-color: #6B7280; /* Tailwind's gray-500 */
            color: #fff;
            text-align: left;
            border-radius: 4px;
            padding: 8px;
            position: absolute;
            z-index: 10;
            bottom: 125%; /* Position above the icon */
            left: 50%;
            margin-left: -125px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </style>

    <!-- Additional JavaScript for dynamic product addition, discount handling, delivery fee toggle, and pickup handling -->
    <script>
        let productCount = <?= isset($product_ids) ? count($product_ids) : 1; ?>;

        function addProductRow() {
            const productContainer = document.getElementById('products-container');

            const productRow = document.createElement('div');
            productRow.className = 'product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4';
            productRow.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="product_id_${productCount}">
                            Product <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select the product from the dropdown menu. This list includes available items that can be added to the customer's order.
                                </span>
                            </span>
                        </label>
                        <select name="product_id[]" id="product_id_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                            <option value="">Select Product</option>
                            <?php foreach($products as $product): ?>
                                <option value="<?= htmlspecialchars($product['id']) ?>">
                                    <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="quantity_${productCount}">
                            Quantity <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified.
                                </span>
                            </span>
                        </label>
                        <input type="number" name="quantity[]" id="quantity_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="packaging_preferences_${productCount}">
                            Packaging Preferences
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery.
                                </span>
                            </span>
                        </label>
                        <input type="text" name="packaging_preferences[]" id="packaging_preferences_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="discount_${productCount}">
                            Apply Discount
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout.
                                </span>
                            </span>
                        </label>
                        <div class="flex items-center mt-1">
                            <input type="checkbox" name="apply_discount[]" id="discount_checkbox_${productCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, ${productCount})">
                            <label for="discount_checkbox_${productCount}" class="ml-2 block text-sm text-gray-700">
                                Yes
                            </label>
                        </div>
                        <div id="discount_fields_${productCount}" class="discount-fields mt-2" style="display: none;">
                            <label class="block text-sm font-medium text-gray-700" for="discount_percentage_${productCount}">
                                Discount Percentage (%) <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                    </span>
                                </span>
                            </label>
                            <input type="number" name="discount_percentage[]" id="discount_percentage_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
                            
                            <label class="block text-sm font-medium text-gray-700 mt-2" for="discount_reason_${productCount}">
                                Discount Reason <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Provide a reason for the discount applied to this product.
                                    </span>
                                </span>
                            </label>
                            <input type="text" name="discount_reason[]" id="discount_reason_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount">
                        </div>
                    </div>
                </div>
                <div class="flex justify-end mt-2">
                    <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)">
                        <i class="bi bi-trash-fill"></i> Remove Product
                    </button>
                </div>
            `;
            productContainer.appendChild(productRow);

            productCount++;
        }

        function removeProductRow(button) {
            const productRow = button.closest('.product-row');
            productRow.remove();
        }

        // Toggle discount fields based on checkbox
        function toggleDiscountFields(checkbox, count) {
            const discountFields = document.getElementById(`discount_fields_${count}`);
            if (checkbox.checked) {
                discountFields.style.display = 'block';
            } else {
                discountFields.style.display = 'none';
                // Clear discount inputs
                discountFields.querySelectorAll('input').forEach(input => input.value = '');
            }
        }

        // Toggle delivery fee field based on free shipping checkbox
        function toggleDeliveryFee() {
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryFeeInput = document.getElementById('delivery_fee');
            if (freeShippingCheckbox.checked) {
                deliveryFeeField.style.display = 'none';
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
            } else {
                deliveryFeeField.style.display = 'block';
                deliveryFeeInput.disabled = false;
            }
        }

        // Toggle specific delivery details based on pickup checkbox
        function togglePickup() {
            const pickupCheckbox = document.getElementById('pickup');
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const deliveryFeeInput = document.getElementById('delivery_fee');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryAddressField = document.getElementById('delivery_address_field');
            const freeShippingField = document.getElementById('free_shipping_field');

            if (pickupCheckbox.checked) {
                // Hide Delivery Address
                deliveryAddressField.style.display = 'none';

                // Uncheck and hide Free Shipping if it's checked
                if (freeShippingCheckbox.checked) {
                    freeShippingCheckbox.checked = false;
                    toggleDeliveryFee();
                }

                // Hide Free Shipping Field
                freeShippingField.style.display = 'none';

                // Disable and hide Delivery Fee
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
                deliveryFeeField.style.display = 'none';
            } else {
                // Show Delivery Address
                deliveryAddressField.style.display = 'block';

                // Show Free Shipping Field
                freeShippingField.style.display = 'flex';

                // Show Delivery Fee based on Free Shipping status
                toggleDeliveryFee();
            }
        }

        // Auto-generate Customer Name based on Contact Number
        function autoGenerateCustomerName() {
            const contactInput = document.getElementById('contact');
            const customerNameInput = document.getElementById('customer_name');
            
            // Extract digits from contact number
            const digits = contactInput.value.replace(/\D/g, '');
            if (digits.length > 0) {
                customerNameInput.value = 'Order_' + digits;
            } else {
                customerNameInput.value = '';
            }
        }

        // Initialize on DOM content loaded
        document.addEventListener('DOMContentLoaded', function() {
            // Add initial product row if none exist
            if (document.getElementById('products-container').children.length === 0) {
                addProductRow();
            }

            // Initialize delivery fee toggle
            toggleDeliveryFee();
            const freeShippingEl = document.getElementById('free_shipping');
            if (freeShippingEl) {
                freeShippingEl.addEventListener('change', toggleDeliveryFee);
            }

            // Initialize pickup toggle
            togglePickup();
            const pickupEl = document.getElementById('pickup');
            if (pickupEl) {
                pickupEl.addEventListener('change', togglePickup);
            }

            // Initialize Customer Name auto-generation
            const contactEl = document.getElementById('contact');
            if (contactEl) {
                contactEl.addEventListener('input', autoGenerateCustomerName);
            }
        });
    </script>

</head>
<body class="bg-gray-100">

    <!-- Include header.php inside the body to prevent HTML structure conflicts -->
    <?php require_once '../../includes/header.php'; ?>

    <!-- Main Container -->
    <main class="container mx-auto p-6">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-teal-600 flex items-center">
                <i class="bi bi-cart-plus mr-2"></i> Add New Order
            </h1>
        </div>

        <!-- Welcome Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <p class="text-gray-700">Fill out the form below to add a new customer order.</p>
        </div>

        <!-- Form Container -->
        <div class="bg-white rounded-lg shadow-lg p-6">
            <?php if (!empty($error)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 flex items-center">
                    <i class="bi bi-exclamation-triangle-fill mr-2"></i>
                    <span><?= htmlspecialchars($error) ?></span>
                </div>
            <?php endif; ?>
            <?php if (!empty($success)): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4 flex items-center">
                    <i class="bi bi-check-circle-fill mr-2"></i>
                    <span><?= htmlspecialchars($success) ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="add_order.php">
                <!-- Customer Details -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2>
                    
                    <div class="flex flex-col md:flex-row md:space-x-6">
                        <div class="flex-1 mb-4 md:mb-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="customer_name">
                                Customer Name <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Automatically generated based on contact number. If unavailable, enter the customer's full name for record purposes.
                                    </span>
                                </span>
                            </label>
                            <input type="text" id="customer_name" name="customer_name" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($customer_name ?? '') ?>" 
                                   placeholder="Auto-generated based on contact number" required>
                        </div>
                        <div class="flex-1 mb-4 md:mb-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="country">
                                Country <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Select the customer’s country to ensure accurate address formatting and delivery options. Default is set to Kuwait (+965).
                                    </span>
                                </span>
                            </label>
                            <select name="country" id="country" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                <?php foreach($countries as $country => $code): ?>
                                    <option value="<?= htmlspecialchars($code) ?>" <?= ($selected_country === $code) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($country . " (" . $code . ")") ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="flex flex-col md:flex-row md:space-x-6 mt-4">
                        <div class="flex-1 mb-4 md:mb-0" id="contact_field">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="contact">
                                Contact Number <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Enter a valid contact number where the customer can be reached for order confirmation or delivery updates. Include area code if applicable.
                                    </span>
                                </span>
                            </label>
                            <input type="text" id="contact" name="contact" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($_POST['contact'] ?? '') ?>" 
                                   required placeholder="Enter contact number without country code">
                        </div>
                        <div class="flex-1" id="delivery_address_field">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_address">
                                Delivery Address
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Provide the full delivery address, including building name, street, area, and any special instructions to facilitate easy and efficient delivery.
                                    </span>
                                </span>
                            </label>
                            <textarea id="delivery_address" name="delivery_address" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars($_POST['delivery_address'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Order Details -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Details</h2>
                    
                    <!-- Priority Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Order Priority
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Choose a priority level for this order based on urgency: Normal for standard processing, Important for prioritized handling, and Quick for immediate attention.
                                </span>
                            </span>
                        </label>
                        <div class="flex space-x-4">
                            <?php
                                $priorities = ['Normal', 'Important', 'Quick'];
                                foreach ($priorities as $priority_option):
                                    $checked = ($priority === $priority_option) ? 'checked' : '';
                            ?>
                                <label class="inline-flex items-center">
                                    <input type="radio" name="priority" value="<?= htmlspecialchars($priority_option) ?>" class="form-radio text-teal-600" <?= $checked ?> required>
                                    <span class="ml-2"><?= htmlspecialchars($priority_option) ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Products Selection -->
                    <div class="mb-4">
                        <div class="flex justify-between items-center mb-2">
                            <label class="block text-sm font-medium text-gray-700">
                                Products <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        List each product the customer wishes to order. Use the ‘Add Another Product’ button to include multiple items within the same order. Ensure accurate product selection and quantity for inventory management.
                                    </span>
                                </span>
                            </label>
                            <button type="button" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 flex items-center gap-2" onclick="addProductRow()">
                                <i class="bi bi-plus-circle-fill"></i> Add Product
                            </button>
                        </div>
                        <div id="products-container">
                            <!-- Product Rows will be added here -->
                            <?php
                            // If form was submitted with errors, repopulate the product rows
                            if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($error) && !empty($product_ids) && is_array($product_ids)) {
                                foreach ($product_ids as $i => $pid) {
                                    ?>
                                    <div class="product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4">
                                        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700" for="product_id_<?= $i ?>">
                                                    Product <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Select the product from the dropdown menu. This list includes available items that can be added to the customer's order.
                                                        </span>
                                                    </span>
                                                </label>
                                                <select name="product_id[]" id="product_id_<?= $i ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                                    <option value="">Select Product</option>
                                                    <?php foreach($products as $product_option): ?>
                                                        <option value="<?= htmlspecialchars($product_option['id']) ?>" <?= ($product_option['id'] == $pid) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)") ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700" for="quantity_<?= $i ?>">
                                                    Quantity <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="number" name="quantity[]" id="quantity_<?= $i ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= isset($quantities[$i]) ? intval($quantities[$i]) : '1' ?>" required>
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700" for="packaging_preferences_<?= $i ?>">
                                                    Packaging Preferences
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= $i ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($packaging_preferences[$i] ?? '') ?>">
                                            </div>
                                            <div>
                                                <label class="block text-sm font-medium text-gray-700" for="discount_<?= $i ?>">
                                                    Apply Discount
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout.
                                                        </span>
                                                    </span>
                                                </label>
                                                <div class="flex items-center mt-1">
                                                    <input type="checkbox" name="apply_discount[]" id="discount_checkbox_<?= $i ?>" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, <?= $i ?>)" <?= isset($apply_discount[$i]) ? 'checked' : '' ?>>
                                                    <label for="discount_checkbox_<?= $i ?>" class="ml-2 block text-sm text-gray-700">
                                                        Yes
                                                    </label>
                                                </div>
                                                <div id="discount_fields_<?= $i ?>" class="discount-fields mt-2" style="display: <?= isset($apply_discount[$i]) ? 'block' : 'none' ?>;">
                                                    <label class="block text-sm font-medium text-gray-700" for="discount_percentage_<?= $i ?>">
                                                        Discount Percentage (%) <span class="text-red-500">*</span>
                                                        <span class="tooltip">
                                                            <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                            <span class="tooltiptext">
                                                                Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                                            </span>
                                                        </span>
                                                    </label>
                                                    <input type="number" name="discount_percentage[]" id="discount_percentage_<?= $i ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage" value="<?= htmlspecialchars($discount_percentages[$i] ?? '') ?>">
                                                    
                                                    <label class="block text-sm font-medium text-gray-700 mt-2" for="discount_reason_<?= $i ?>">
                                                        Discount Reason <span class="text-red-500">*</span>
                                                        <span class="tooltip">
                                                            <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                            <span class="tooltiptext">
                                                                Provide a reason for the discount applied to this product.
                                                            </span>
                                                        </span>
                                                    </label>
                                                    <input type="text" name="discount_reason[]" id="discount_reason_<?= $i ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($discount_reasons[$i] ?? '') ?>">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="flex justify-end mt-2">
                                            <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)">
                                                <i class="bi bi-trash-fill"></i> Remove Product
                                            </button>
                                        </div>
                                    </div>
                                    <?php
                                }
                            } else {
                                // Add one default product row
                                ?>
                                <div class="product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4">
                                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="product_id_0">
                                                Product <span class="text-red-500">*</span>
                                                <span class="tooltip">
                                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                    <span class="tooltiptext">
                                                        Select the product from the dropdown menu. This list includes available items that can be added to the customer's order.
                                                    </span>
                                                </span>
                                            </label>
                                            <select name="product_id[]" id="product_id_0" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                                <option value="">Select Product</option>
                                                <?php foreach($products as $product_option): ?>
                                                    <option value="<?= htmlspecialchars($product_option['id']) ?>">
                                                        <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)") ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="quantity_0">
                                                Quantity <span class="text-red-500">*</span>
                                                <span class="tooltip">
                                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                    <span class="tooltiptext">
                                                        Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified.
                                                    </span>
                                                </span>
                                            </label>
                                            <input type="number" name="quantity[]" id="quantity_0" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="packaging_preferences_0">
                                                Packaging Preferences
                                                <span class="tooltip">
                                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                    <span class="tooltiptext">
                                                        Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery.
                                                    </span>
                                                </span>
                                            </label>
                                            <input type="text" name="packaging_preferences[]" id="packaging_preferences_0" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="discount_0">
                                                Apply Discount
                                                <span class="tooltip">
                                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                    <span class="tooltiptext">
                                                        Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout.
                                                    </span>
                                                </span>
                                            </label>
                                            <div class="flex items-center mt-1">
                                                <input type="checkbox" name="apply_discount[]" id="discount_checkbox_0" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, 0)">
                                                <label for="discount_checkbox_0" class="ml-2 block text-sm text-gray-700">
                                                    Yes
                                                </label>
                                            </div>
                                            <div id="discount_fields_0" class="discount-fields mt-2" style="display: none;">
                                                <label class="block text-sm font-medium text-gray-700" for="discount_percentage_0">
                                                    Discount Percentage (%) <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="number" name="discount_percentage[]" id="discount_percentage_0" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
                                                
                                                <label class="block text-sm font-medium text-gray-700 mt-2" for="discount_reason_0">
                                                    Discount Reason <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Provide a reason for the discount applied to this product.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="text" name="discount_reason[]" id="discount_reason_0" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="flex justify-end mt-2">
                                        <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)">
                                            <i class="bi bi-trash-fill"></i> Remove Product
                                        </button>
                                    </div>
                                </div>
                                <?php
                            }
                            ?>
                        </div>
                        <button type="button" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 flex items-center gap-2" onclick="addProductRow()">
                            <i class="bi bi-plus-circle-fill"></i> Add Another Product
                        </button>
                    </div>

                    <!-- Delivery Details -->
                    <hr class="my-6">
                    <div class="mb-6">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">Delivery Details</h2>
                        <!-- Pickup Checkbox -->
                        <div class="flex items-center mb-4">
                            <input type="checkbox" id="pickup" name="pickup" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= isset($_POST['pickup']) ? 'checked' : '' ?> onchange="togglePickup()">
                            <label for="pickup" class="ml-2 block text-sm text-gray-700">
                                Customer Pickup
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Select this option if the customer will pick up the order directly from our kitchen, eliminating the need for delivery.
                                    </span>
                                </span>
                            </label>
                        </div>
                        <!-- Delivery Section -->
                        <div id="delivery_details">
                            <!-- Free Shipping Field with Assigned ID -->
                            <div class="flex items-center mb-4" id="free_shipping_field">
                                <input type="checkbox" id="free_shipping" name="free_shipping" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= isset($_POST['free_shipping']) && !isset($_POST['pickup']) ? 'checked' : '' ?> onchange="toggleDeliveryFee()">
                                <label for="free_shipping" class="ml-2 block text-sm text-gray-700">
                                    Free Shipping
                                    <span class="tooltip">
                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                        <span class="tooltiptext">
                                            Select this option if the customer qualifies for free shipping based on promotional offers or order amount. Delivery fees will automatically update.
                                        </span>
                                    </span>
                                </label>
                            </div>
                            <div id="delivery_fee_field" class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_fee">
                                    Delivery Fee (KWD)
                                    <span class="tooltip">
                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                        <span class="tooltiptext">
                                            Enter any applicable delivery fee in Kuwaiti Dinar (KWD). This field will automatically set to 0 if ‘Free Shipping’ is selected or if pickup is chosen.
                                        </span>
                                    </span>
                                </label>
                                <input type="number" step="0.01" min="0" name="delivery_fee" id="delivery_fee" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                       value="<?= isset($_POST['delivery_fee']) && !isset($_POST['pickup']) ? htmlspecialchars($_POST['delivery_fee']) : '0.00' ?>" 
                                       <?= (isset($_POST['free_shipping']) && !isset($_POST['pickup'])) ? 'disabled' : '' ?> required>
                            </div>
                        </div>
                        <!-- Delivery Date and Time -->
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_datetime">
                                Delivery Date and Time
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Choose a specific date and time for the order delivery or pickup. Ensure the date aligns with the customer’s availability and our schedule to avoid delays.
                                    </span>
                                </span>
                            </label>
                            <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($_POST['delivery_datetime'] ?? '') ?>" required>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="mb-6">
                        <button type="submit" class="w-full bg-teal-500 text-white px-4 py-3 rounded-lg hover:bg-teal-600 transition duration-300 flex justify-center items-center gap-2">
                            <i class="bi bi-plus-lg"></i> Add Order
                        </button>
                    </div>
            </form>
        </div>

        <!-- Footer -->
        <div class="mt-12 text-center text-gray-600">
            &copy; <?= date("Y") ?> Kaak Alia Bakery. All rights reserved.
        </div>
    </main>

    <!-- Bootstrap JS Bundle (optional if using Bootstrap components) -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Flatpickr JS for Date Picker -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <!-- Flatpickr Initialization -->
    <script>
        flatpickr("#delivery_datetime", {
            enableTime: true,
            dateFormat: "Y-m-d\\TH:i",
            minDate: "today"
        });
    </script>

    <!-- Optional: Bootstrap Tooltip Initialization (if using tooltips in future) -->
    <script>
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('.tooltip'))
        tooltipTriggerList.forEach(function (tooltipTriggerEl) {
            var tooltipText = tooltipTriggerEl.querySelector('.tooltiptext');
            tooltipTriggerEl.addEventListener('mouseenter', function() {
                tooltipText.style.visibility = 'visible';
                tooltipText.style.opacity = '1';
            });
            tooltipTriggerEl.addEventListener('mouseleave', function() {
                tooltipText.style.visibility = 'hidden';
                tooltipText.style.opacity = '0';
            });
        });
    </script>

</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) i want you to create edit order page, and make it better