-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm12.cs
More file actions
862 lines (764 loc) · 40.1 KB
/
Copy pathForm12.cs
File metadata and controls
862 lines (764 loc) · 40.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
using System.Configuration;
namespace H1
{
public partial class Form12 : Form
{
// Colors
private Color navbarColor = Color.FromArgb(44, 62, 80);
private Color headerColor = Color.FromArgb(52, 152, 219);
private Color whiteColor = Color.White;
private Color lightGrayColor = Color.FromArgb(240, 240, 240);
// Database connection - made configurable
private string connectionString = @"Data Source=ABDULSABOOR190\SQLEXPRESS;Initial Catalog=sabbbb;Integrated Security=True;Encrypt=False";
// Current operator ID (replace with actual operator ID from login)
private int currentOperatorId = 3;
// Selected trip ID for updates/deletes
private int selectedTripId = -1;
private int defaultPolicyId = 1; // Default cancellation policy ID
public Form12()
{
InitializeComponent();
// Try to load connection string from config if available
try
{
if (ConfigurationManager.ConnectionStrings["DefaultConnection"] != null)
{
connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
}
catch (Exception)
{
// Use the default connection string
}
// Set default dates
dtpStartDate.Value = DateTime.Now.AddDays(1);
dtpEndDate.Value = DateTime.Now.AddDays(8);
LoadData();
}
private void LoadData()
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// Check if cancellation policy exists and create a default one if not
EnsureDefaultCancellationPolicy(conn);
// Load categories
LoadCategories(conn);
// Load trips
LoadTrips(conn);
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading data: " + ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
LoadSampleData(); // Fallback to sample data
}
}
private void EnsureDefaultCancellationPolicy(SqlConnection conn)
{
try
{
// Check if table exists
string checkTableQuery = @"
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CancellationPolicy')
SELECT 1 ELSE SELECT 0";
SqlCommand checkTableCmd = new SqlCommand(checkTableQuery, conn);
int tableExists = (int)checkTableCmd.ExecuteScalar();
if (tableExists == 0)
{
// Create the table if it doesn't exist
string createTableQuery = @"
CREATE TABLE CancellationPolicy (
policy_id INT PRIMARY KEY IDENTITY(1,1),
refund_percent DECIMAL(5,2) NOT NULL,
deadline_days INT NOT NULL,
terms TEXT NOT NULL
)";
SqlCommand createTableCmd = new SqlCommand(createTableQuery, conn);
createTableCmd.ExecuteNonQuery();
}
// Check if any policy exists
string checkQuery = "SELECT COUNT(*) FROM CancellationPolicy";
SqlCommand checkCmd = new SqlCommand(checkQuery, conn);
int policyCount = (int)checkCmd.ExecuteScalar();
if (policyCount == 0)
{
// Create a default policy
string createQuery = @"
INSERT INTO CancellationPolicy (refund_percent, deadline_days, terms)
VALUES (100, 7, 'Full refund if canceled 7 days before the trip.');
SELECT SCOPE_IDENTITY();";
SqlCommand createCmd = new SqlCommand(createQuery, conn);
decimal result = (decimal)createCmd.ExecuteScalar();
defaultPolicyId = (int)result;
}
else
{
// Get the ID of an existing policy to use as default
string getIdQuery = "SELECT TOP 1 policy_id FROM CancellationPolicy";
SqlCommand getIdCmd = new SqlCommand(getIdQuery, conn);
defaultPolicyId = (int)getIdCmd.ExecuteScalar();
}
}
catch (Exception ex)
{
MessageBox.Show("Error setting up cancellation policy: " + ex.Message, "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void LoadCategories(SqlConnection conn)
{
try
{
// Check if table exists
string checkTableQuery = @"
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TourCategory')
SELECT 1 ELSE SELECT 0";
SqlCommand checkTableCmd = new SqlCommand(checkTableQuery, conn);
int tableExists = (int)checkTableCmd.ExecuteScalar();
if (tableExists == 0)
{
// Create the table if it doesn't exist
string createTableQuery = @"
CREATE TABLE TourCategory (
category_id INT PRIMARY KEY IDENTITY(1,1),
name VARCHAR(50) UNIQUE NOT NULL,
description TEXT
)";
SqlCommand createTableCmd = new SqlCommand(createTableQuery, conn);
createTableCmd.ExecuteNonQuery();
}
string query = "SELECT category_id AS CategoryID, name AS Name, description AS Description FROM TourCategory";
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
DataTable categories = new DataTable();
adapter.Fill(categories);
if (categories.Rows.Count > 0)
{
cmbCategory.DataSource = categories;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "CategoryID";
}
else
{
// If no categories exist, try to create some default ones
CreateDefaultCategories(conn);
// Try loading again
adapter.Fill(categories);
cmbCategory.DataSource = categories;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "CategoryID";
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading categories: " + ex.Message, "Database Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CreateDefaultCategories(SqlConnection conn)
{
try
{
string[] categoryNames = { "Adventure", "Cultural", "Beach", "Mountain", "City Tour", "Wildlife", "Historical" };
string[] descriptions = {
"High-energy outdoor activities",
"Immersive cultural experiences",
"Relaxing beach vacations",
"Mountain hiking and climbing",
"Urban exploration tours",
"Wildlife safaris and encounters",
"Historical sites and museums"
};
for (int i = 0; i < categoryNames.Length; i++)
{
string query = @"
INSERT INTO TourCategory (name, description)
VALUES (@name, @description)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@name", categoryNames[i]);
cmd.Parameters.AddWithValue("@description", descriptions[i]);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error creating default categories: " + ex.Message, "Database Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadTrips(SqlConnection conn)
{
try
{
// Check if tables exist
EnsureTripTablesExist(conn);
// Check if operator profile exists for the current operator ID
EnsureOperatorProfileExists(conn);
string query = @"
SELECT
t.trip_id AS TripID,
t.title AS Title,
t.description AS Description,
t.destination AS Destination,
tc.category_id AS CategoryID,
cat.name AS Category,
t.start_date AS StartDate,
t.end_date AS EndDate,
t.price AS Price,
t.max_capacity AS MaxCapacity,
t.difficulty_level AS Difficulty,
CASE WHEN t.is_active = 1 THEN 'Active' ELSE 'Inactive' END AS Status,
t.policy_id AS PolicyID
FROM Trip t
LEFT JOIN TripCategory tc ON t.trip_id = tc.trip_id
LEFT JOIN TourCategory cat ON tc.category_id = cat.category_id
WHERE t.operator_id = @operatorId";
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
adapter.SelectCommand.Parameters.AddWithValue("@operatorId", currentOperatorId);
DataTable trips = new DataTable();
adapter.Fill(trips);
dgvTrips.DataSource = trips;
FormatTripsGrid();
}
catch (Exception ex)
{
MessageBox.Show("Error loading trips: " + ex.Message, "Database Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void EnsureTripTablesExist(SqlConnection conn)
{
try
{
// Check if Trip table exists
string checkTripTableQuery = @"
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Trip')
SELECT 1 ELSE SELECT 0";
SqlCommand checkTripTableCmd = new SqlCommand(checkTripTableQuery, conn);
int tripTableExists = (int)checkTripTableCmd.ExecuteScalar();
if (tripTableExists == 0)
{
// Create the Trip table if it doesn't exist
string createTripTableQuery = @"
CREATE TABLE Trip (
trip_id INT PRIMARY KEY IDENTITY(1,1),
operator_id INT NOT NULL,
policy_id INT NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
destination VARCHAR(255) NOT NULL,
start_date DATE NOT NULL,
end_date DATE NOT NULL,
max_capacity INT NOT NULL,
price DECIMAL(10,2) NOT NULL,
difficulty_level VARCHAR(10) NOT NULL CHECK (difficulty_level IN ('easy', 'medium', 'hard')),
sustainability_score DECIMAL(3,1),
is_active BIT DEFAULT 1
)";
SqlCommand createTripTableCmd = new SqlCommand(createTripTableQuery, conn);
createTripTableCmd.ExecuteNonQuery();
}
// Check if TripCategory table exists
string checkTripCategoryTableQuery = @"
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TripCategory')
SELECT 1 ELSE SELECT 0";
SqlCommand checkTripCategoryTableCmd = new SqlCommand(checkTripCategoryTableQuery, conn);
int tripCategoryTableExists = (int)checkTripCategoryTableCmd.ExecuteScalar();
if (tripCategoryTableExists == 0)
{
// Create the TripCategory table if it doesn't exist
string createTripCategoryTableQuery = @"
CREATE TABLE TripCategory (
trip_id INT NOT NULL,
category_id INT NOT NULL,
PRIMARY KEY (trip_id, category_id)
)";
SqlCommand createTripCategoryTableCmd = new SqlCommand(createTripCategoryTableQuery, conn);
createTripCategoryTableCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error ensuring trip tables exist: " + ex.Message, "Database Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void EnsureOperatorProfileExists(SqlConnection conn)
{
try
{
// Check if AppUser table exists
string checkAppUserTableQuery = @"
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'AppUser')
SELECT 1 ELSE SELECT 0";
SqlCommand checkAppUserTableCmd = new SqlCommand(checkAppUserTableQuery, conn);
int appUserTableExists = (int)checkAppUserTableCmd.ExecuteScalar();
if (appUserTableExists == 0)
{
// Create the AppUser table if it doesn't exist
string createAppUserTableQuery = @"
CREATE TABLE AppUser (
user_id INT IDENTITY(1,1) PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
registration_status VARCHAR(50) NOT NULL,
role VARCHAR(50) NOT NULL,
is_active BIT DEFAULT 1 NOT NULL,
created_at DATETIME DEFAULT GETDATE() NOT NULL
)";
SqlCommand createAppUserTableCmd = new SqlCommand(createAppUserTableQuery, conn);
createAppUserTableCmd.ExecuteNonQuery();
}
// Check if TourOperatorProfile table exists
string checkOperatorTableQuery = @"
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'TourOperatorProfile')
SELECT 1 ELSE SELECT 0";
SqlCommand checkOperatorTableCmd = new SqlCommand(checkOperatorTableQuery, conn);
int operatorTableExists = (int)checkOperatorTableCmd.ExecuteScalar();
if (operatorTableExists == 0)
{
// Create the TourOperatorProfile table if it doesn't exist
string createOperatorTableQuery = @"
CREATE TABLE TourOperatorProfile (
user_id INT PRIMARY KEY,
company_name VARCHAR(100) NOT NULL,
contact_no VARCHAR(20) NOT NULL,
license_no VARCHAR(50) UNIQUE NOT NULL,
description TEXT
)";
SqlCommand createOperatorTableCmd = new SqlCommand(createOperatorTableQuery, conn);
createOperatorTableCmd.ExecuteNonQuery();
}
// Check if the current operator exists
string checkOperatorQuery = @"
SELECT COUNT(*) FROM TourOperatorProfile WHERE user_id = @operatorId";
SqlCommand checkOperatorCmd = new SqlCommand(checkOperatorQuery, conn);
checkOperatorCmd.Parameters.AddWithValue("@operatorId", currentOperatorId);
int operatorExists = (int)checkOperatorCmd.ExecuteScalar();
if (operatorExists == 0)
{
// Check if user exists in AppUser table
string checkUserQuery = @"
SELECT COUNT(*) FROM AppUser WHERE user_id = @userId";
SqlCommand checkUserCmd = new SqlCommand(checkUserQuery, conn);
checkUserCmd.Parameters.AddWithValue("@userId", currentOperatorId);
int userExists = (int)checkUserCmd.ExecuteScalar();
if (userExists == 0)
{
// Create a user entry
string createUserQuery = @"
INSERT INTO AppUser (user_id, email, password_hash, registration_status, role, is_active)
VALUES (@userId, @email, @passwordHash, 'approved', 'operator', 1)";
SqlCommand createUserCmd = new SqlCommand(createUserQuery, conn);
createUserCmd.Parameters.AddWithValue("@userId", currentOperatorId);
createUserCmd.Parameters.AddWithValue("@email", "operator" + currentOperatorId + "@example.com");
createUserCmd.Parameters.AddWithValue("@passwordHash", "dummypasswordhash");
createUserCmd.ExecuteNonQuery();
}
// Create an operator profile
string createOperatorQuery = @"
INSERT INTO TourOperatorProfile (user_id, company_name, contact_no, license_no, description)
VALUES (@operatorId, @companyName, @contactNo, @licenseNo, @description)";
SqlCommand createOperatorCmd = new SqlCommand(createOperatorQuery, conn);
createOperatorCmd.Parameters.AddWithValue("@operatorId", currentOperatorId);
createOperatorCmd.Parameters.AddWithValue("@companyName", "Default Tour Operator");
createOperatorCmd.Parameters.AddWithValue("@contactNo", "123-456-7890");
createOperatorCmd.Parameters.AddWithValue("@licenseNo", "LIC-" + currentOperatorId);
createOperatorCmd.Parameters.AddWithValue("@description", "Default tour operator description");
createOperatorCmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error ensuring operator profile exists: " + ex.Message, "Database Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormatTripsGrid()
{
if (dgvTrips.Columns.Count > 0)
{
dgvTrips.Columns["TripID"].Visible = false;
dgvTrips.Columns["CategoryID"].Visible = false;
dgvTrips.Columns["Description"].Visible = false;
if (dgvTrips.Columns.Contains("PolicyID"))
dgvTrips.Columns["PolicyID"].Visible = false;
dgvTrips.Columns["Title"].HeaderText = "Trip Title";
dgvTrips.Columns["Destination"].HeaderText = "Destination";
dgvTrips.Columns["StartDate"].HeaderText = "Start Date";
dgvTrips.Columns["EndDate"].HeaderText = "End Date";
dgvTrips.Columns["Price"].HeaderText = "Price (USD)";
dgvTrips.Columns["MaxCapacity"].HeaderText = "Capacity";
dgvTrips.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dgvTrips.RowHeadersVisible = false;
dgvTrips.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgvTrips.AllowUserToAddRows = false;
}
}
private void btnCreateTrip_Click(object sender, EventArgs e)
{
if (ValidateTripForm())
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// Ensure all required tables exist
EnsureTripTablesExist(conn);
EnsureOperatorProfileExists(conn);
EnsureDefaultCancellationPolicy(conn);
SqlTransaction transaction = conn.BeginTransaction();
try
{
// 1. Insert trip
string tripQuery = @"
INSERT INTO Trip (
operator_id, title, description, destination,
start_date, end_date, max_capacity, price,
difficulty_level, is_active, policy_id
)
VALUES (
@operatorId, @title, @description, @destination,
@startDate, @endDate, @maxCapacity, @price,
@difficulty, 1, @policyId
);
SELECT SCOPE_IDENTITY();";
SqlCommand tripCmd = new SqlCommand(tripQuery, conn, transaction);
tripCmd.Parameters.AddWithValue("@operatorId", currentOperatorId);
tripCmd.Parameters.AddWithValue("@title", txtTitle.Text);
tripCmd.Parameters.AddWithValue("@description", txtDescription.Text);
tripCmd.Parameters.AddWithValue("@destination", txtDestination.Text);
tripCmd.Parameters.AddWithValue("@startDate", dtpStartDate.Value);
tripCmd.Parameters.AddWithValue("@endDate", dtpEndDate.Value);
tripCmd.Parameters.AddWithValue("@maxCapacity", int.Parse(txtCapacity.Text));
tripCmd.Parameters.AddWithValue("@price", decimal.Parse(txtPrice.Text));
tripCmd.Parameters.AddWithValue("@difficulty", cmbDifficulty.SelectedItem.ToString().ToLower());
tripCmd.Parameters.AddWithValue("@policyId", defaultPolicyId);
int tripId = Convert.ToInt32(tripCmd.ExecuteScalar());
// 2. Insert trip category
string categoryQuery = @"
INSERT INTO TripCategory (trip_id, category_id)
VALUES (@tripId, @categoryId)";
SqlCommand categoryCmd = new SqlCommand(categoryQuery, conn, transaction);
categoryCmd.Parameters.AddWithValue("@tripId", tripId);
categoryCmd.Parameters.AddWithValue("@categoryId", cmbCategory.SelectedValue);
categoryCmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Trip created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearForm();
LoadTrips(conn); // Refresh the trips list
}
catch (Exception ex)
{
transaction.Rollback();
throw new Exception("Database error during trip creation: " + ex.Message);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error creating trip: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private bool ValidateTripForm()
{
if (string.IsNullOrWhiteSpace(txtTitle.Text))
{
MessageBox.Show("Please enter a trip title", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (string.IsNullOrWhiteSpace(txtDestination.Text))
{
MessageBox.Show("Please enter a destination", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (dtpStartDate.Value.Date < DateTime.Now.Date)
{
MessageBox.Show("Start date cannot be in the past", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (dtpStartDate.Value >= dtpEndDate.Value)
{
MessageBox.Show("End date must be after start date", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (!decimal.TryParse(txtPrice.Text, out decimal price) || price <= 0)
{
MessageBox.Show("Please enter a valid price", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (!int.TryParse(txtCapacity.Text, out int capacity) || capacity <= 0)
{
MessageBox.Show("Please enter a valid capacity", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
if (cmbCategory.SelectedValue == null)
{
MessageBox.Show("Please select a category", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
private void ClearForm()
{
txtTitle.Clear();
txtDescription.Clear();
txtDestination.Clear();
if (cmbCategory.Items.Count > 0) cmbCategory.SelectedIndex = 0;
dtpStartDate.Value = DateTime.Now.AddDays(1);
dtpEndDate.Value = DateTime.Now.AddDays(8);
txtPrice.Clear();
txtCapacity.Clear();
if (cmbDifficulty.Items.Count > 0) cmbDifficulty.SelectedIndex = 0;
btnCreateTrip.Enabled = true;
btnUpdateTrip.Enabled = false;
btnDeleteTrip.Enabled = false;
selectedTripId = -1;
}
private void dgvTrips_SelectionChanged(object sender, EventArgs e)
{
if (dgvTrips.SelectedRows.Count > 0)
{
DataRowView row = (DataRowView)dgvTrips.SelectedRows[0].DataBoundItem;
LoadTripDetails(row.Row);
}
}
private void LoadTripDetails(DataRow trip)
{
try
{
selectedTripId = Convert.ToInt32(trip["TripID"]);
txtTitle.Text = trip["Title"].ToString();
txtDescription.Text = trip["Description"].ToString();
txtDestination.Text = trip["Destination"].ToString();
// Handle potential null or missing CategoryID
if (trip["CategoryID"] != DBNull.Value && cmbCategory.Items.Count > 0)
{
cmbCategory.SelectedValue = trip["CategoryID"];
}
dtpStartDate.Value = (trip["StartDate"] != DBNull.Value) ?
(DateTime)trip["StartDate"] : DateTime.Now;
dtpEndDate.Value = (trip["EndDate"] != DBNull.Value) ?
(DateTime)trip["EndDate"] : DateTime.Now.AddDays(1);
txtPrice.Text = trip["Price"].ToString();
txtCapacity.Text = trip["MaxCapacity"].ToString();
// Set difficulty (adapt for case sensitivity)
string difficulty = trip["Difficulty"].ToString();
for (int i = 0; i < cmbDifficulty.Items.Count; i++)
{
if (cmbDifficulty.Items[i].ToString().Equals(difficulty, StringComparison.OrdinalIgnoreCase))
{
cmbDifficulty.SelectedIndex = i;
break;
}
}
btnUpdateTrip.Enabled = true;
btnDeleteTrip.Enabled = true;
btnCreateTrip.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show("Error loading trip details: " + ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnUpdateTrip_Click(object sender, EventArgs e)
{
if (selectedTripId <= 0)
{
MessageBox.Show("Please select a trip to update", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (ValidateTripForm())
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
try
{
// 1. Update trip
string tripQuery = @"
UPDATE Trip SET
title = @title,
description = @description,
destination = @destination,
start_date = @startDate,
end_date = @endDate,
max_capacity = @maxCapacity,
price = @price,
difficulty_level = @difficulty
WHERE trip_id = @tripId";
SqlCommand tripCmd = new SqlCommand(tripQuery, conn, transaction);
tripCmd.Parameters.AddWithValue("@title", txtTitle.Text);
tripCmd.Parameters.AddWithValue("@description", txtDescription.Text);
tripCmd.Parameters.AddWithValue("@destination", txtDestination.Text);
tripCmd.Parameters.AddWithValue("@startDate", dtpStartDate.Value);
tripCmd.Parameters.AddWithValue("@endDate", dtpEndDate.Value);
tripCmd.Parameters.AddWithValue("@maxCapacity", int.Parse(txtCapacity.Text));
tripCmd.Parameters.AddWithValue("@price", decimal.Parse(txtPrice.Text));
tripCmd.Parameters.AddWithValue("@difficulty", cmbDifficulty.SelectedItem.ToString().ToLower());
tripCmd.Parameters.AddWithValue("@tripId", selectedTripId);
tripCmd.ExecuteNonQuery();
// 2. Update trip category (delete old and insert new)
string deleteCategoryQuery = "DELETE FROM TripCategory WHERE trip_id = @tripId";
SqlCommand deleteCmd = new SqlCommand(deleteCategoryQuery, conn, transaction);
deleteCmd.Parameters.AddWithValue("@tripId", selectedTripId);
deleteCmd.ExecuteNonQuery();
string insertCategoryQuery = @"
INSERT INTO TripCategory (trip_id, category_id)
VALUES (@tripId, @categoryId)";
SqlCommand insertCmd = new SqlCommand(insertCategoryQuery, conn, transaction);
insertCmd.Parameters.AddWithValue("@tripId", selectedTripId);
insertCmd.Parameters.AddWithValue("@categoryId", cmbCategory.SelectedValue);
insertCmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Trip updated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearForm();
LoadTrips(conn); // Refresh the trips list
}
catch (Exception ex)
{
transaction.Rollback();
throw new Exception("Database error during trip update: " + ex.Message);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error updating trip: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnDeleteTrip_Click(object sender, EventArgs e)
{
if (selectedTripId <= 0)
{
MessageBox.Show("Please select a trip to delete", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var confirm = MessageBox.Show("Are you sure you want to delete this trip?", "Confirm Delete",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirm == DialogResult.Yes)
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
try
{
// Check if this trip has any bookings
string checkBookingsQuery = @"
SELECT COUNT(*) FROM Booking WHERE trip_id = @tripId";
SqlCommand checkCmd = new SqlCommand(checkBookingsQuery, conn, transaction);
checkCmd.Parameters.AddWithValue("@tripId", selectedTripId);
int bookingCount = (int)checkCmd.ExecuteScalar();
if (bookingCount > 0)
{
// If there are bookings, just set the trip to inactive instead of deleting
string deactivateQuery = @"
UPDATE Trip SET is_active = 0 WHERE trip_id = @tripId";
SqlCommand deactivateCmd = new SqlCommand(deactivateQuery, conn, transaction);
deactivateCmd.Parameters.AddWithValue("@tripId", selectedTripId);
deactivateCmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Trip has existing bookings and has been deactivated instead of deleted.",
"Trip Deactivated", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// First delete from TripCategory (foreign key constraint)
string deleteCategoryQuery = "DELETE FROM TripCategory WHERE trip_id = @tripId";
SqlCommand deleteCategoryCmd = new SqlCommand(deleteCategoryQuery, conn, transaction);
deleteCategoryCmd.Parameters.AddWithValue("@tripId", selectedTripId);
deleteCategoryCmd.ExecuteNonQuery();
// Check and delete any itinerary items
string deleteItineraryQuery = "DELETE FROM ItineraryItem WHERE trip_id = @tripId";
SqlCommand deleteItineraryCmd = new SqlCommand(deleteItineraryQuery, conn, transaction);
deleteItineraryCmd.Parameters.AddWithValue("@tripId", selectedTripId);
deleteItineraryCmd.ExecuteNonQuery();
// Then delete from Trip
string deleteTripQuery = "DELETE FROM Trip WHERE trip_id = @tripId";
SqlCommand deleteTripCmd = new SqlCommand(deleteTripQuery, conn, transaction);
deleteTripCmd.Parameters.AddWithValue("@tripId", selectedTripId);
deleteTripCmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Trip deleted successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
ClearForm();
LoadTrips(conn); // Refresh the trips list
}
catch
{
transaction.Rollback();
throw;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error deleting trip: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnClearForm_Click(object sender, EventArgs e)
{
ClearForm();
}
private void LoadSampleData()
{
// Fallback sample data for categories
DataTable categories = new DataTable();
categories.Columns.Add("CategoryID", typeof(int));
categories.Columns.Add("Name", typeof(string));
categories.Columns.Add("Description", typeof(string));
categories.Rows.Add(1, "Adventure", "High-energy outdoor activities");
categories.Rows.Add(2, "Cultural", "Immersive cultural experiences");
categories.Rows.Add(3, "Beach", "Relaxing beach vacations");
categories.Rows.Add(4, "Mountain", "Mountain hiking and climbing");
categories.Rows.Add(5, "City Tour", "Urban exploration tours");
categories.Rows.Add(6, "Wildlife", "Wildlife safaris and encounters");
categories.Rows.Add(7, "Historical", "Historical sites and museums");
cmbCategory.DataSource = categories;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "CategoryID";
// Fallback sample data for trips
DataTable trips = new DataTable();
trips.Columns.Add("TripID", typeof(int));
trips.Columns.Add("Title", typeof(string));
trips.Columns.Add("Description", typeof(string));
trips.Columns.Add("Destination", typeof(string));
trips.Columns.Add("CategoryID", typeof(int));
trips.Columns.Add("Category", typeof(string));
trips.Columns.Add("StartDate", typeof(DateTime));
trips.Columns.Add("EndDate", typeof(DateTime));
trips.Columns.Add("Price", typeof(decimal));
trips.Columns.Add("MaxCapacity", typeof(int));
trips.Columns.Add("Difficulty", typeof(string));
trips.Columns.Add("Status", typeof(string));
trips.Columns.Add("PolicyID", typeof(int));
trips.Rows.Add(1, "Paris City Tour", "Explore the beautiful city of Paris", "Paris", 5, "City Tour",
new DateTime(2025, 5, 15), new DateTime(2025, 5, 20), 1200m, 25, "Easy", "Active", 1);
trips.Rows.Add(2, "Alpine Adventure", "Challenging mountain hikes", "Swiss Alps", 4, "Mountain",
new DateTime(2025, 6, 10), new DateTime(2025, 6, 17), 1800m, 15, "Hard", "Active", 1);
trips.Rows.Add(3, "Safari Experience", "African wildlife safari", "Serengeti", 6, "Wildlife",
new DateTime(2025, 7, 5), new DateTime(2025, 7, 12), 2500m, 12, "Medium", "Active", 1);
dgvTrips.DataSource = trips;
FormatTripsGrid();
}
}
}